【问题标题】:redux-observable - await async actions and convert them to Promise using rootEpicredux-observable - 等待异步操作并使用 rootEpic 将它们转换为 Promise
【发布时间】:2018-08-03 15:40:26
【问题描述】:

next.js repository 中的示例展示了我们如何将根史诗转换为 Promise,因此可以像 ajax 一样进行 await 异步操作:

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 更简单的方法 - 我的意思是调用一次并等待三个操作。

【问题讨论】:

    标签: redux promise rxjs redux-observable


    【解决方案1】:

    我偶然在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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 2015-12-13
      相关资源
      最近更新 更多