Redux-observable:如何等待多个异步请求然后在史诗中执行操作 [英] Redux-observable: how to wait for multiple async requests then perform action in an epic

查看:75
本文介绍了Redux-observable:如何等待多个异步请求然后在史诗中执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在触发另一个操作之前等待下面的两个 http 请求完成.但是,http 请求没有被触发.仅触发了 DASHBOARD_INIT 操作:

I'd like to wait for the two http requests below to finish before triggering another action. However, the http requests were not fired. Only the DASHBOARD_INIT action was triggered:

export const dashboardInitEpic = (action$: any) =>
    action$.ofType(InitActionTypes.DASHBOARD_INIT)
        .switchMap((action: ActionDashboardInit) =>
           zip$(
             of$(fetchConfig(action.payload)),
             of$(fetchPermission(action.payload))
           ).switchMap(() =>
           zip$(
             action$.ofType(ActionTypes.FETCH_CONFIG_FULFILLED).take(1),
             action$.ofType(ActionTypes.FETCH_PERMISSION_FULFILLED).take(1)
           ).switchMap(() => of$({type: InitActionTypes.DASHBOARD_INIT_COMPLETE}))
         )
      );

为了触发 http 请求,我必须执行以下操作,这并不是我想要的.Concat 强制 http 请求按顺序执行,下面的代码按顺序侦听 FETCH_CONFIG_FULFILLED 和 FETCH_PERMISSION_FULFILLED,有时会中断,具体取决于 fetchConfig 的响应是否先返回.

To get the http requests fired, I had to do the following which is not exactly what I want. Concat forces the http requests to be in sequence and the code below listens to FETCH_CONFIG_FULFILLED and FETCH_PERMISSION_FULFILLED in sequence, which breaks sometimes depending on whether fetchConfig's response comes back first.

export const dashboardInitEpic = (action$: any) =>
    action$.ofType(InitActionTypes.DASHBOARD_INIT)
      .mergeMap((action: ActionDashboardInit) =>
         concat$(
           of$(fetchConfig(action.payload)),
           of$(fetchPermission(action.payload)),
           action$.ofType(ActionTypes.FETCH_CONFIG_FULFILLED).take(1),
           action$.ofType(ActionTypes.FETCH_PERMISSION_FULFILLED)
             .take(1)
             .switchMap(() => of$({type: InitActionTypes.DASHBOARD_INIT_COMPLETE}))
      )
    );

非常感谢任何帮助.被这个问题困了好几天了.非常感谢!

Any help is greatly appreciated. Have been stuck on this for a few days. Thanks a lot!

推荐答案

试试这个:

export const dashboardInitEpic = (action$: any) =>
  action$
    .ofType(InitActionTypes.DASHBOARD_INIT)
    .mergeMap((action: ActionDashboardInit) =>
      concat$(
        of$(fetchConfig(action.payload)),
        of$(fetchPermission(action.payload)),
        zip$(
          action$.ofType(ActionTypes.FETCH_CONFIG_FULFILLED).take(1),
          action$.ofType(ActionTypes.FETCH_PERMISSION_FULFILLED).take(1)
        ).mapTo({ type: InitActionTypes.DASHBOARD_INIT_COMPLETE })
      )
    );

这篇关于Redux-observable:如何等待多个异步请求然后在史诗中执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆