[英]Node.js - mysql query inside foreach
我有這樣的代碼結構:
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正在阻止,但查詢是非阻止的。 我試圖使用諾言:
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.all,然后等待它們全部完成,然后再嘗試訪問response
。
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
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.