问题
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