gpt4 book ai didi

javascript - Node.js - foreach 内的 mysql 查询

转载 作者:太空宇宙 更新时间:2023-11-03 23:06:43 24 4
gpt4 key购买 nike

我有这样的代码结构:

connection.query(query1,function(err,rows) {
var response = [];
//doing something with rows
rows.forEach(function(item) {
connection.query(queryItem,function(err,rows) {
//doing something
result = rows[0].field;
//and want to push it to an array
response.push(result);
});
});
console.log(response); //empty
});

我知道 forEach 是阻塞的,但查询是非阻塞的。我尝试使用 promise :

connection.query(query1,function(err,rows) {
var response = [];
//doing something with rows
rows.forEach(function(item) {
var promise = new Promise(function(resolve,reject) {
connection.query(queryItem,function(err,rows) {
//doing something
result = rows[0].field;
//and want to push it to an array
resolve(result);
});
});
promise.then(function(result) {
console.log(result); //ok
response.push(result) //not ok, result is empty
});
});
console.log(response); //empty
});

但这并没有帮助。如何从非阻塞函数将值插入数组并在之后使用它?

最佳答案

创建 Promise 是朝着正确方向迈出的一步,但您需要更进一步,将 Promise 聚合到一个数组中并传递给 Promise.all,然后等待它们全部完成,然后再尝试访问响应

connection.query(query1,function(err,rows) {
var response = [];
//doing something with rows
Promise.all(rows.map(function(item) {
var promise = new Promise(function(resolve,reject) {
connection.query(queryItem,function(err,rows) {
//doing something
result = rows[0].field;
//and want to push it to an array
resolve(result);
});
});
return promise.then(function(result) {
console.log(result); //ok
response.push(result) //ok
});
}).then(function () {
console.log(response); //not empty
});
});

关于javascript - Node.js - foreach 内的 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32916486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com