简体   繁体   English

等待两个异步功能完成,然后在Node.js中继续

[英]Wait for two async functions to finish then continue in Node.js

I'm working on an application in Node.js where I'm calling an async function twice, and assign the value to a global variable. 我正在使用Node.js中的应用程序,在该应用程序中我两次调用了异步函数,并将该值分配给全局变量。

The issue is that I want to use the result of the two calls to do something else, but this something else doesn't wait for the result to be assigned. 问题是我想使用这两次调用的结果来做其他事情,但是其他事情并没有等待分配结果。

Here's my code: 这是我的代码:

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

How can I wait for the two functions to finish, before executing a + b ? 我如何在执行a + b之前等待两个函数完成?

As foo returns a Promise you should mark your function as asyncronus with async keyword and wait for the foo function to respond with the await keyword. 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)
}

You can use Promise.all here, to wait for the two promises and then work with their data: 您可以在此处使用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}); } 

Instead of using .then() you can use await . 除了使用.then()还可以使用await So this: 所以这:

foo(x).then(data=>{
    a = data;
});

would be like this: 会是这样的:

a = await foo(x);

Same goes for the other function. 其他功能也一样。 This will cause your execution to wait until the functions return. 这将导致您的执行要等到函数返回。 Notice however that in order to use await you would have to wrap the statement that uses it, or even better the whole block, in a function that is declared as aync .You can find more on how to use async here . 但是请注意,要使用await必须将使用它的语句甚至更好的是将整个块包装在一个声明为aync的函数中。您可以在此处找到有关如何使用async 信息

Try this: 尝试这个:

 //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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM