5

我正在努力弄清楚如何catch在我的史诗中的错误处理程序中触发多个操作。

我已经成功地弄清楚了如何使用 thunk-middleware 在我的史诗中成功的异步调用上触发多个操作。见下文:

const editDomainsEpic = (action$) =>
  action$
    .ofType(EDIT_DOMAINS)
    .mergeMap((action) =>
      Rx.Observable.fromPromise(api.editDomains(action.payload))
        // Here we are using Redux thunk middleware to execute
        // a function instead of just dispatching an action
        // so that we can disptach two actions
        // ----------------- vvv
        .map((domain) => (dispatch) => {
          // Display Growl Notifications
          dispatch(
            displayGrowlNotification(
              MESSAGE_TYPES.SUCCESS,
              `${domain.name} was saved`
            )
          )
          // Fire Success Action
          dispatch({
            type: EDIT_DOMAINS_SUCCESS,
            payload: { domain }
          })
        })
        .catch((error) => Rx.Observable.of({
          type: EDIT_DOMAINS_ERROR,
          payload: { error }
        }))
        .takeUntil(action$.ofType(EDIT_DOMAINS_CANCEL))
    )

任何人都可以指导我如何catch返回或触发两个可观察到的动作,这些动作将像我成功的方式一样被调度?

4

1 回答 1

12

Observable.of() supports an arbitrary number of arguments and will emit them all sequentially one after the other, so to emit more than one action in your catch, you just add more arguments.

With that knowledge at hand, you can also use it to dispatch multiple actions for success instead of emitting a thunk and imperatively calling dispatch yourself.

const editDomainsEpic = (action$) =>
  action$
    .ofType(EDIT_DOMAINS)
    .mergeMap((action) =>
      Rx.Observable.fromPromise(api.editDomains(action.payload))
        .mergeMap((domain) => Rx.Observable.of(
          displayGrowlNotification(
            MESSAGE_TYPES.SUCCESS,
            `${domain.name} was saved`
          ), {
            type: EDIT_DOMAINS_SUCCESS,
            payload: { domain }
          }
        ))
        .catch((error) => Rx.Observable.of({
          type: EDIT_DOMAINS_ERROR,
          payload: { error }
        }, {
          type: ANOTHER_ONE,
          payload: 'something-else'
        }))
        .takeUntil(action$.ofType(EDIT_DOMAINS_CANCEL))
    )

This would be more idiomatic RxJS (and thus redux-observable) but it's not necessarily a requirement.

于 2017-02-21T07:48:19.423 回答