admin管理员组

文章数量:1276735

I am wanting to do something like the following in a React ponent:

const someArray = [/*stuff*/]
const results = []
someArray.forEach(async item => {

  const result = await someAsyncFunction(item)
  results.push(result)
})

How can I know when all the results have returned then do something?

If I was using $q, in AngularJS, I could do

var results = []
someArray.forEach(function(item) {
  var result = someAsyncFunctionThatReturnsAPromise(item);
  results.push(result);
});

$q.all(results).then(function() {
  // do something
});

I am wanting to do something like the following in a React ponent:

const someArray = [/*stuff*/]
const results = []
someArray.forEach(async item => {

  const result = await someAsyncFunction(item)
  results.push(result)
})

How can I know when all the results have returned then do something?

If I was using $q, in AngularJS, I could do

var results = []
someArray.forEach(function(item) {
  var result = someAsyncFunctionThatReturnsAPromise(item);
  results.push(result);
});

$q.all(results).then(function() {
  // do something
});
Share Improve this question asked Oct 20, 2017 at 20:41 dfritchdfritch 3591 gold badge3 silver badges16 bronze badges 8
  • 3 use Promise.all(/* Your Promise Array */).then(...)? – CRice Commented Oct 20, 2017 at 20:42
  • You're making your code synchronous, so isn't the order of operations guaranteed? Meaning that if you put console.log(results) after your forEach loop, it would have all the values. That's the beauty of async/await. – Chase DeAnda Commented Oct 20, 2017 at 20:45
  • 1 @ChaseDeAnda Unfortunately you can't use forEach with async / await, but a basic for loop will work.. – Keith Commented Oct 20, 2017 at 20:47
  • @Keith Ah, okay thanks I didn't know that. OP check out this post stackoverflow./questions/37576685/… – Chase DeAnda Commented Oct 20, 2017 at 20:48
  • As @CRice said but you will have to remove the async await – Kevin Farrugia Commented Oct 20, 2017 at 20:51
 |  Show 3 more ments

2 Answers 2

Reset to default 7

You'd do exactly the same thing as if it wasn't a React ponent:

Promise.all(someArray.map(someAsyncFunction)).then(results => {
  // do stuff with results
});

Of course you can also use q, which $q is based on. It's up to you.

In addition to the answer from Felix, inside an async function, you can also await on the results from Promise.all(), so:

const results = await Promise.all(someArray.map(someAsyncFunction));

本文标签: javascriptHow to await multiple async await requests in ReactStack Overflow