如何执行相关的顺序调用和 return 包含所有响应的数组?
How to execute dependent, sequential calls and return an array with all responses?
我有一个 redux-observable 史诗,它轮询一个 API 并且我正在尝试执行三个相关的顺序 http 请求并将所有响应收集到一个数组中。
toArray() 在这种情况下永远不会执行,因为 concatMap() 尚未完成。我试图将调用移动到 mergeMap() 内部并在那里收集数组,但只有最后一个调用在数组中。
timer(0, POLLING_INTERVAL).pipe(
concatMap(() => from(fetchApi(url1))),
concatMap(response => {
const url2 = 'URL based on first response';
return from(fetchApi(url2));
}),
concatMap(response => {
const url3 = 'URL based on second response';
return from(fetchApi(url3));
}),
toArray(), // expected [{response1}, {response2}, {response3}]
map(data => ({
type: ActionTypes.FETCH_SUCCESS,
payload: { data },
})),
catchError(error =>
of({
type: ActionTypes.FETCH_FAILED,
payload: { error },
}),
),
takeUntil(
action$.pipe(
ofType(ActionTypes.CANCEL_POLLING),
),
),
);
这取决于你想做什么。 toArray()
不会帮助你,因为 timer
永远不会完成并且 toArray()
仅在其源完成时发出。
也许您正在寻找这样的东西:
timer(0, POLLING_INTERVAL).pipe(
concatMap(() => from(fetchApi(url1)).pipe(
concatMap(response1 => {
const url2 = 'URL based on first response';
return forkJoin([of(response1), fetchApi(url2)]);
}),
concatMap(([response1, response2]) => {
const url3 = 'URL based on second response';
return forkJoin([of(response1), of(response2), fetchApi(url3)]);
}),
)),
map(data => ({
type: ActionTypes.FETCH_SUCCESS,
payload: { data },
})),
...
我有一个 redux-observable 史诗,它轮询一个 API 并且我正在尝试执行三个相关的顺序 http 请求并将所有响应收集到一个数组中。
toArray() 在这种情况下永远不会执行,因为 concatMap() 尚未完成。我试图将调用移动到 mergeMap() 内部并在那里收集数组,但只有最后一个调用在数组中。
timer(0, POLLING_INTERVAL).pipe(
concatMap(() => from(fetchApi(url1))),
concatMap(response => {
const url2 = 'URL based on first response';
return from(fetchApi(url2));
}),
concatMap(response => {
const url3 = 'URL based on second response';
return from(fetchApi(url3));
}),
toArray(), // expected [{response1}, {response2}, {response3}]
map(data => ({
type: ActionTypes.FETCH_SUCCESS,
payload: { data },
})),
catchError(error =>
of({
type: ActionTypes.FETCH_FAILED,
payload: { error },
}),
),
takeUntil(
action$.pipe(
ofType(ActionTypes.CANCEL_POLLING),
),
),
);
这取决于你想做什么。 toArray()
不会帮助你,因为 timer
永远不会完成并且 toArray()
仅在其源完成时发出。
也许您正在寻找这样的东西:
timer(0, POLLING_INTERVAL).pipe(
concatMap(() => from(fetchApi(url1)).pipe(
concatMap(response1 => {
const url2 = 'URL based on first response';
return forkJoin([of(response1), fetchApi(url2)]);
}),
concatMap(([response1, response2]) => {
const url3 = 'URL based on second response';
return forkJoin([of(response1), of(response2), fetchApi(url3)]);
}),
)),
map(data => ({
type: ActionTypes.FETCH_SUCCESS,
payload: { data },
})),
...