简体   繁体   English

如何在React中等待多个异步等待请求

[英]How to await multiple async await requests in React

I am wanting to do something like the following in a React component: 我想在React组件中执行以下操作:

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 如果我在AngularJS中使用$ q,我可以做到

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

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

You'd do exactly the same thing as if it wasn't a React component: 你做的完全相同,就好像它不是一个React组件:

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

Of course you can also use q , which $q is based on. 当然你也可以使用q$q基于。 It's up to you. 由你决定。

除了Felix的答案,在async函数中,你还可以await Promise.all()的结果,所以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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