【发布时间】: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