首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >存储数据,发送数据

存储数据,发送数据
EN

Stack Overflow用户
提问于 2022-05-17 06:25:29
回答 1查看 36关注 0票数 0
代码语言:javascript
复制
let test = [];
myarray.forEach((obj) => {
  db.query('select * from table', (err, res) => {
    // can't use return res.send here bcoz its in foreach loop

    test.push(res);
  });
});

return res.send(test);

Output :
[ ]
"DATA"

首先获取空数组,但第二次获取数据。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-17 06:52:25

这是因为您正在获取数据,而不是等待它。

您的代码是这样执行的:

  1. 起动前级回路
  2. 在每次迭代中启动一个请求
  3. 精加工前馈回路
  4. 返回阵列
  5. ..。
  6. 在发送数据之后,您的请求将在这里完成。

目标是循环遍历数组中的每个项,发送请求,等待所有响应,然后继续发送响应。这是最好的承诺&异步/等待。阅读更多的这里

我就是这样解决这个问题的。

代码语言:javascript
复制
async function runQueries() {
    // Configure array to store all promises
    const promises = []

    // Iterate through each item (this probably takes 0.001 seconds)
    myarray.forEach(obj => {
        // Run the query and store the ongoing request in the promises array
        promises.push(new Promise((resolve, reject) => {
            db.query('select * from table', (err, res) => {
                if (err) {
                    // If there was an error, send it to reject which will be caught in the try/catch
                    return reject(err)
                }

                // Return the success response
                resolve(res)
            })
        }))
    })

    // try/catch to handle any issues.
    try {
        // wait for all ongoing requests to finish and return either a response or error
        const result = await Promise.all(promises)

        // Return the result
        res.send(result)
    } catch (err) {
        console.log(err)
        
        // Send any error instead
        res.status(500).send(err)
    }
}

编辑1:

这不是经过测试的,只是为了解释我处理这类问题的方法。

编辑2:

错误,并封装在异步函数中。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72269079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档