最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Wait for two async functions to finish then continue in Node.js - Stack Overflow

programmeradmin1浏览0评论

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.

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?

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.

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?

Share Improve this question edited Sep 10, 2018 at 14:04 gyc 4,3606 gold badges35 silver badges55 bronze badges asked Sep 10, 2018 at 13:51 user9518022user9518022
Add a comment  | 

3 Answers 3

Reset to default 9

You can use Promise.all here, to wait for the two promises and then work with their data:

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});
}

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.

 async function someFunction(){   
  let x = 'abcd';
  let a = await  foo(x);

  x = 'efgh';
  let b = await foo(x);
  console.log(a + b)
}

Instead of using .then() you can use 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.

发布评论

评论列表(0)

  1. 暂无评论