存储foreach数据并在foreach后发送


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"

第一次获得空数组,但第二次获得数据。

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

你的代码是这样执行的:

  1. Start foreach loop
  2. 每次迭代启动一个请求
  3. 完成foreach循环
  4. <
  5. 返回数组/gh>
  6. 在数据发送后,您的请求在这里完成。

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

这就是我将如何解决它。

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:

输入错误,用async函数包装

最新更新