RX.JS Redux Observable Multiple Get requests at same time

蓝咒 提交于 2020-05-15 10:19:10

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/47482610/rx-js-redux-observable-multiple-get-requests-at-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!