【问题标题】:React async API call inside .map() function from actions [duplicate]从动作中反应.map()函数内的异步API调用[重复]
【发布时间】:2020-11-06 10:21:37
【问题描述】:

我是 React JS 的新手。在我的应用程序中,我面临需要使用不同的 url 多次调用 API 的情况,例如 apiurl.com/abc、apiurl.com/xyz。这些 abc 和 xyz 存储在一个数组中。因此,我想使用 .map() 更改 url 以进行多个 api 调用。但是在 .map() 中,异步等待是行不通的,所以如果有的话,请寻找一些解决方案。我已经经历了一些可能的解决方案,比如 promises,但无法实现。

这是我的代码:

export const someAction = () => async (dispatch, param) => {
let myArray = ["abc", "xyz"];
let id= "";
param1 = "someauthcode";
myArray.map((x) => {
    id = x;
    const myResponse = await loaders.myResponseApi(param1, id); *//This does not work as await should be in async call*
});
dispatch({ type: types.ARRAY_API, payload: myResponse });

}

所以我们的想法是使用 apiurl.com/abc、apiurl.com/xyz 进行 2 次 api 调用。我在不同的文件中构建了 url (apiurl.com)。

提前致谢。

【问题讨论】:

  • 你可以使用 Promise.all 。检查这个javascript.info/promise-api
  • 您的地图函数缺少async 前缀。此代码将失败。
  • 正如@HarmandeepSinghKalsi 所暗示的,Array#map 不支持等待异步事件。但是,您可以返回一个 Promises 数组
  • 你想用 API 调用做什么。您是否需要访问地图功能中的响应?如果没有,@HarmandeepSinghKalsi 建议的 Promise.all 将起作用。如果您确实需要访问响应,请尝试将 async (x) 添加到 map 函数的开头。
  • 您是要等待所有响应返回后再分派任何内容,还是要在响应进来时分派?

标签: javascript reactjs redux jsx


【解决方案1】:

把你的数组变成一个promise数组,然后使用Promise.all

export const someAction = () => async(dispatch) => {


   try {
     const payload = await Promise.all(myArray.map(id => loaders.myResponseApi(param1,id)));
     dispatch({type:types.ARRAY_API,payload});
   } catch(err) {
     // an error occurred in at least one of the promises
   }

}

【讨论】:

  • 太棒了!非常感谢您为此抽出一些时间。 :)
【解决方案2】:

您可以使用传统的forwhile 循环来代替.map()

export const someAction = () => async (dispatch, param) => {
    let myArray = ["abc", "xyz"];
    let id= "";
    param1 = "someauthcode";
    let i = 0;
    while (i < myArray.length) {
        id = myArray[i];
        const myResponse = await loaders.myResponseApi(param1, id);
        // handle response here...
        i++;
    }
}

【讨论】:

  • 会试试这个。谢谢:)
猜你喜欢
  • 2020-06-11
  • 2022-01-19
  • 2023-03-25
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 2022-11-26
相关资源
最近更新 更多