我有这样的代码结构:
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/