如何在Express JS的for循环中发送res.json()?

问题描述 投票:0回答:1

当前端触发API调用时,我试图发送一个json响应,但我无法发送 res.json() 当我从for循环中获取数据时,我需要写一个查询来搜索多个Table。我正在写一个查询来搜索多个Tables。我使用的是RethinkDB。

我想 res.json() 但我不明白我做错了什么。 :(

Thanks in advence

兽人

以下是代码和 提琴链接 也是。

const express = require("express");
const router = express.Router();
const moment = require('moment');
const r = require('rethinkdb');
const tableNameDB = ['assets', 'alerts',  'destinations']


router.post('/', (req, res, next) => {
        let resData = []
        let searchValue = req.body.searchValue,
            tableName = req.body.tableName;
        newCallForSearch(res, searchValue, resData)
    })

function newCallForSearch (res, searchValue, resData){
    let anArray = ['captain']
    for(var i = 0; i<tableNameDB.length; i++){
        let tabName = tableNameDB[i]
        r.table(tableNameDB[i]).filter(function(doc) {
            return doc.coerceTo('string').match(searchValue);
        }).run(rethink_conn, (err, cur) => {
           // console.log(cur)
            if (err) {
                return 0
            } else {
                cur.toArray((err, result) => {
                    if (err) {
                        return 0
                    } else if (result) {
                        let Results = []
                        Results = Object.values(result).slice(0,10)
                        var newResults = Results.map(function() {
                            resData = Object.assign({'tableName': tabName},{'data' : result});
                            anArray.push(resData)
                        })
                    }
                })    
                
            }
                
        })
    }   
    res.status(200);
    res.json(anArray); 
}

module.exports = router;
javascript node.js express rethinkdb
1个回答
0
投票

RethinkDb是一个功能型数据库,所以用功能型的方式来使用它,会产生最小的阻力。我们可以通过写更少的代码来完成更多的任务。

你可以使用 Promise.all 来运行多个子查询,并将结果传递给 res.send -

const search = (table = "", query = "", limit = 10) =>
  r.table(table)
  .filter(doc => doc.coerceTo("string").match(query))
  .toArray()
  .slice(0, limit)
  .do(data => ({ table, data }))

const tables =
  ['assets', 'alerts',  'destinations']

const subqueries =
  tables.map(t => search(t, "foo").run(rethink_conn)) // <-- search each table

Promise.all(subqueries) // <-- run all subqueries
  .then(result => {     // <-- handle success
    res.status(200)
    res.json(result)
  })
  .catch(e => {         // <-- handle failure
    res.status(500)
    res.send(e.message)
  })

或使用 .union 以产生一个单一的查询 -

const search = (table = "", query = "", limit = 10) =>
  r.table(table)
  .filter(doc => doc.coerceTo("string").match(query))
  .toArray()
  .slice(0, limit)
  .do(data => ({ table, data }))

const searchAll = (tables = [], query = "", limit = 10) =>
  tables.reduce
    ( (r, t) => r.union(search(t, query, limit)) // <-- union
    , r.expr([]) // <-- if no tables are supplied, return empty result
    )

const tables =
  ['assets', 'alerts',  'destinations']

searchAll(tables, "foo") // <-- single rethink expr
  .run(rethink_conn)     // <-- run returns a promise
  .then(result => {      // <-- handle success
    res.status(200)
    res.json(result)
  })
  .catch(e => {          // <-- handle failure
    res.status(500)
    res.send(e.message)
  })

我想说的是,建议使用 filter 在你的原帖中

.filter(doc => doc.coerceTo("string").match(query))

这个速度很快,但也很马虎。匹配 query 对任何 doc的价值,但也是 doc的钥匙。如果 doc 是一个复杂的嵌套文档,它也会匹配它们。用户要注意。

© www.soinside.com 2019 - 2024. All rights reserved.