简体   繁体   中英

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:

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. Only first data is dispatched. It is inside loop and I expect it to dispatch for all the data from loop.

How can I achieve this ?

Thank you

As soon as you return , The return statement exits the function. 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.

You can use Promise.all(promises) to create a promise that resolves when all the child promises have resolved. You can collect promises into an array as you create them, and later return Promise.all(promises) to represent them all:

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)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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