存储 foreach 数据并在 foreach 之后发送
store foreach data and send after 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"
第一次获取空数组,第二次获取数据。
这是因为您正在获取数据而不是等待它。
你的代码是这样执行的:
- 开始foreach循环
- 每次迭代都启动一个请求
- 完成 foreach 循环
- Return数组
- ...
- 发送数据后,您的请求在此处完成。
目标是遍历数组中的每个项目,发送请求,等待所有响应,然后继续发送响应。这最好通过 promises & async/await 来实现。阅读更多 here.
这就是我要解决的问题。
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:
打字错误并包含在异步函数中
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"
第一次获取空数组,第二次获取数据。
这是因为您正在获取数据而不是等待它。
你的代码是这样执行的:
- 开始foreach循环
- 每次迭代都启动一个请求
- 完成 foreach 循环
- Return数组
- ...
- 发送数据后,您的请求在此处完成。
目标是遍历数组中的每个项目,发送请求,等待所有响应,然后继续发送响应。这最好通过 promises & async/await 来实现。阅读更多 here.
这就是我要解决的问题。
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:
打字错误并包含在异步函数中