redux-observable - 等待异步操作并使用 rootEpic 将它们转换为 Promise
redux-observable - await async actions and convert them to Promise using rootEpic
next.js repository 中的示例显示了我们如何将根史诗转换为 Promise,因此可以 await
像 ajax
:
这样的异步操作
static async getInitialProps ({ store, isServer }) {
const resultAction = await rootEpic(
of(actions.fetchCharacter(isServer)),
store
).toPromise() // we need to convert Observable to Promise
store.dispatch(resultAction)
return { isServer }
}
我想知道如何才能 await
多个动作。我设法这样做了:
const actions = await Promise.all([
rootEpic(of(fetchCharacterOne()), store).toPromise(),
rootEpic(of(fetchCharacterTwo()), store).toPromise(),
rootEpic(of(fetchCharacterThree()), store).toPromise(),
]);
actions.forEach(store.dispatch);
...但我想知道是否有比每次调用 rootEpic
更简单的方法 - 我的意思是调用一次并等待三个操作。
我在 universal-rxjs-ajax 文档中无意中找到了答案。这就是我要找的代码:
const initialData$ = of(
fetchCharacterOne(),
fetchCharacterTwo(),
fetchCharacterThree(),
);
const actions = await rootEpic(initialData$, store)
.pipe(toArray()) // buffers all emitted actions until Epic completes
.toPromise();
actions.forEach(store.dispatch);
next.js repository 中的示例显示了我们如何将根史诗转换为 Promise,因此可以 await
像 ajax
:
static async getInitialProps ({ store, isServer }) {
const resultAction = await rootEpic(
of(actions.fetchCharacter(isServer)),
store
).toPromise() // we need to convert Observable to Promise
store.dispatch(resultAction)
return { isServer }
}
我想知道如何才能 await
多个动作。我设法这样做了:
const actions = await Promise.all([
rootEpic(of(fetchCharacterOne()), store).toPromise(),
rootEpic(of(fetchCharacterTwo()), store).toPromise(),
rootEpic(of(fetchCharacterThree()), store).toPromise(),
]);
actions.forEach(store.dispatch);
...但我想知道是否有比每次调用 rootEpic
更简单的方法 - 我的意思是调用一次并等待三个操作。
我在 universal-rxjs-ajax 文档中无意中找到了答案。这就是我要找的代码:
const initialData$ = of(
fetchCharacterOne(),
fetchCharacterTwo(),
fetchCharacterThree(),
);
const actions = await rootEpic(initialData$, store)
.pipe(toArray()) // buffers all emitted actions until Epic completes
.toPromise();
actions.forEach(store.dispatch);