[英]Node.js wait until async functions are complete, then continue with the rest of the code
[英]Wait for two async functions to finish then continue in Node.js
我正在使用Node.js中的應用程序,在該應用程序中我兩次調用了異步函數,並將該值分配給全局變量。
問題是我想使用這兩次調用的結果來做其他事情,但是其他事情並沒有等待分配結果。
這是我的代碼:
var a;
var b;
let x = 'abcd';
foo(x).then(data=>{
a = data;
});
x = 'efgh';
foo(x).then(data=>{
b = data;
});
console.log(a + b); // for example
我如何在執行a + b
之前等待兩個函數完成?
當foo
返回Promise時,您應該使用async
關鍵字將函數標記為asyncronus,並等待foo
函數以await
關鍵字響應。
async function someFunction(){
let x = 'abcd';
let a = await foo(x);
x = 'efgh';
let b = await foo(x);
console.log(a + b)
}
您可以在此處使用Promise.all
,等待兩個promise,然后使用它們的數據:
let promises = []; let x = 'abcd'; promises.push(foo(x)) x = 'efgh'; promises.push(foo(x)) Promise.all(promises).then(([a, b]) => { console.log(a, b); // for example }); function foo(d) { return Promise.resolve({somePaddingData:"", d}); }
嘗試這個:
//using setInterval to wait for completion //a function which returns a callback function foo(x,callback){ //do some computaion on x callback(x); }; //to store the response let result = []; //calling foo method twice parallely foo("123",(data)=>{ result.push(data); }); foo("456",(data)=>{ result.push(data); }); //waiting till the above functions are done with the execution //setInterval function will check every 100 ms(can be any value) if the length of the result array is 2 let timer = setInterval(() => { if (result.length == 2) { clearInterval(timer); //prints the two value console.log(result.join("")) } }, 100);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.