简体   繁体   中英

RX.JS Redux Observable Multiple Get requests at same time

I am trying to set up an observable that currently receives an array of location IDs and then makes a get request for all of these at once and waits for the response for them all. Here is a sample:

const fetchPhotosEpic = action$ =>
    action$.ofType(LOCATIONS_RECEIVED)
    .map(action => action.payload)
    .mergeMap((data) =>  {
        let promiseArray = data.map(location => Observable.fromPromise(axios.get(photosUrl(location.id))))
        return Observable.forkJoin(
           promiseArray
        )
    })
    .map(responses => responses.map((response) => response.data.location))

Where data looks like:

[
    {
        id: "aoeuaeu",
        name: "Test"
    },
  ...
]

The issue I have right now is I get a 404 on one of the requests and it's messing everything up. I am probably doing something wrong as I am just learning RX. Any help would be great!

You can try adding a catch to each call and returning a new observable with the error message, which should stop the forkJoin failing if one request fails. You can then either filter out the failures, or add logic to handle them in your final .map. eg.

const fetchPhotosEpic = action$ =>
    action$.ofType(LOCATIONS_RECEIVED)
    .map(action => action.payload)
    .mergeMap((data) => {
        let promiseArray = data.map(location => {
            return Observable.fromPromise(axios.get(photosUrl(location.id)))
                .catch(error => Observable.of({error}))
      })
      return Observable.forkJoin(
          promiseArray
      )
  })
 .filter(response => !Boolean(response.error))
 .map(responses => responses.map((response) => response.data.location))

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