Javascript 在将操作传递给还原器之前,如何确保返回所有调用并将其推入数组?

Javascript 在将操作传递给还原器之前,如何确保返回所有调用并将其推入数组?,javascript,asynchronous,promise,redux,react-redux,Javascript,Asynchronous,Promise,Redux,React Redux,我有一个ActionCreator,它为每个place_id向Google Places调用API。然后我想将响应推送到一个数组中,然后将其传递给我的reducer。问题是我在阵列有机会被填满之前就开始调度它。我如何着手解决这个问题 export function placesFetchBookmarks(place_ids) { return (dispatch) => { const newPlaces = []; place_ids.forEach(place_i

我有一个ActionCreator,它为每个place_id向Google Places调用API。然后我想将响应推送到一个数组中,然后将其传递给我的reducer。问题是我在阵列有机会被填满之前就开始调度它。我如何着手解决这个问题

export function placesFetchBookmarks(place_ids) {
  return (dispatch) => {
    const newPlaces = [];
    place_ids.forEach(place_id => {
      const request = { placeId: place_id };
      const service = new google.maps.places.PlacesService(document.createElement('div'));
      service.getDetails(request, (place, status) => {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          newPlaces.push(place);
        } else {
          dispatch(placeDetailsHasErrored(true));
        }
      });
    });
    dispatch({
      type: PLACES_FETCH_DATA_SUCCESS,
      places: newPlaces
    })
  }
}

使用
Promise.all
并让异步调用解析promises。像这样的方法应该会奏效:

const promises = place_ids.map(place_id => {
    return new Promise((resolve, reject) => {
        const request = { placeId: place_id };
        const service = new google.maps.places.PlacesService(document.createElement('div'));
        service.getDetails(request, (place, status) => {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                resolve(place);
            } else {
                reject();
            }
        });
    });
});

Promise.all(promises)
    .then(places => dispatch({
      type: PLACES_FETCH_DATA_SUCCESS,
      places
    }))
    .catch(() => dispatch(placeDetailsHasErrored(true)))