[英]How to wait for multiple API calls from a Redux action creator?
Lets say I am calling a dispatch method in my actions : 可以说我在动作中调用了一个调度方法:
return dispatch(add_data(data)).then(function(response){console.log("Done")}
and my add_data
method looks like: 和我的add_data
方法看起来像:
export function add_data(data){
return (dispatch, getState) => {
for(var i in data){
var data = {'url': data[i]}
return dispatch(myApi({url: "some_url", method: "POST", data: data,}
)).then(response => {
console.log(response)
return response.json()
}).then(response => {
console.log(response)
return dispatch({response, type: types.ADD_DATA})
})
}
}
}
It is working for only first
data. 它仅适用于first
数据。 Only first
data is dispatched. 仅调度first
数据。 It is inside loop and I expect it to dispatch
for all the data from loop. 它在循环内部,我希望它为循环中的所有数据dispatch
。
How can I achieve this ? 我该如何实现?
Thank you 谢谢
As soon as you return
, The return
statement exits the function. 一旦return
,则return
语句退出该函数。 If you don't want to return from a function in the middle of the loop, don't return
from it in the middle of the loop. 如果您不想在循环中间从函数返回,请不要在循环中间从函数return
。
You can use Promise.all(promises)
to create a promise that resolves when all the child promises have resolved. 您可以使用Promise.all(promises)
创建一个承诺,该承诺在所有子承诺都已解决时会解决。 You can collect promises into an array as you create them, and later return Promise.all(promises)
to represent them all: 您可以在创建它们时将它们收集到一个数组中,然后返回Promise.all(promises)
来表示它们:
export function add_data(data){
return (dispatch, getState) => {
var promises = [];
for (var key in data) {
var itemData = {'url': data[key]}
var promise = myApi({
url: "some_url",
method: "POST",
data: itemData
}).then(
response => response.json()
).then(response => {
dispatch({response, type: types.ADD_DATA})
})
promises.push(promise)
}
return Promise.all(promises)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.