[SOLVED]在For循环中使用异步功能

时间:2020-05-24 14:02:28

标签: javascript reactjs async-await

我有一个数组,需要为每个索引调用API端点。解决该问题后,我需要将其附加到该元素中。我想在为数组的每个索引完成此操作后返回更新的数组。

我尝试以这种方式使用async-await

// Let input be [{'x': 1, 'y': 2}, {'x': 11, 'y': 22}, ...]

async function hello(input) {
  await input.forEach(element => {
     fetch(url, options)
     .then((res) => {
        element['z'] = res
     })  
  })
  return input
}

我需要使用此功能来更新我的状态

hello(data)
.then((res: any) => {

    this.setState((prevState) => ({
        ...prevState,
        inputData: res,
    }))
})

问题是我还需要一个强制渲染才能显示键“ z”。 如何解决呢? 我对使用异步等待没有太多经验,所以不确定我是否正确使用它。

2 个答案:

答案 0 :(得分:3)

正确的方法是使用Promise.all并返回调用方函数将使用的promise,因为您希望将整个更新的输入值设置为状态。

在您的情况下,forEach不会返回承诺,因此等待它是没有用的。

此外,如果您在forEach函数中使用await,则需要在所有promise都解决后才能提供让hello函数的.then方法调用。 Promise.all为您做到

function hello(input) {
  const promises = [];
  input.forEach(element => {
     promises.push(
          fetch(url, options)
             .then(res => res.json()
             .then((result) => { 
                // return the updated object
                return {...element, z: result};
              })
     ) 
  });
  return Promise.all(promises);
}

...
hello(data)
.then((res: any) => {
    this.setState((prevState) => ({
        ...prevState,
        inputData: res,
    }))
})

P.S。请注意,取回的响应也需要使用res.json()

进行调用

答案 1 :(得分:1)

异步/等待不会在使用回调(forEach,地图等)的循环中工作

您可以使用for..of循环来实现结果。

尝试一下,让我知道它是否有效。

function getResult() {
  return new Promise((resolve) => {
    fetch(url, options)
      .then((res) => {
        return resolve(res);
      })
  })

}

async function hello(input) {

  for (let element of input) {
    let res = await getResult(element);
    element['z'] = res;
  }
}