[英]Await is not working for function call in nodejs?
我有一個名為looper2()的函數,該函數接受一個數據數組,我試圖從mysql數據庫中獲取每個數據的ID。一切正常,但是當它仍然表示該函數時,我的nodejs並未等待該函數等待。
var noloop = [];
noloop = await looper2(json_array1);
console.log("db id returns",noloop)
console.log("no loop",noloop[0]); //im getting this undefined
function looper2(){
return new Promise(function(resolve, reject) {
// Do async job
for(var i=0;i<json_array1.length;i++){
var sl = "select id from json where name ="+db.escape(json_array1[i]);
db.query(sl, function(err,result) {
if (err) throw err;
console.log("individual id:", result)
noloop.push(result)
});
}
resolve(noloop)
});
}
問題是在looper2函數中,您可以在forLoop之后立即解決問題,而不必等待db查詢完成。 您應該改為在數據庫查詢全部完成后進行解析
function looper2(){
return new Promise(function(resolve, reject) {
// Do async job
for(var i=0;i<json_array1.length;i++){
var sl = "select id from json where name ="+db.escape(json_array1[i]);
db.query(sl, function(err,result) {
if (err) throw err;
console.log("individual id:", result)
noloop.push(result)
if(noloop.length == json_array1.length) {
resolve(noloop)
}
});
}
});
}
沒有異步功能,您將無法使用await。 因此,您必須創建一個自可執行函數以使用如下所示的await。 而且,如果您在循環內使用promise,則可以使用promise.all
函數,您可以用來解析所有未完成的promise。
(async () => {
var noloop = [];
noloop = await looper2(json_array1);
console.log(noloop);
})();
function async looper2(){
const promises = [];
for(var i=0;i<json_array1.length;i++){
var sl = "select id from json where name ="+db.escape(json_array1[i]);
db.query(sl, function(err,result) {
if (err) throw err;
promises.push(new Promise(result));
});
}
return Promise.all(promises)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.