MySQL查詢我的代碼,這樣的結構:Node.js的 - 裏面的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
});
但它沒有幫助。我如何從非阻塞函數中將值推入數組並在之後使用它?
這是天生的諾言還是藍鳥? – Selfish
我是節點中的新手。要求( '承諾');可能是本機的,我不知道=) –