【问题标题】:How to handle promise rejection when using fromPromise (rxjs5.5)使用 fromPromise (rxjs5.5) 时如何处理 Promise 拒绝
【发布时间】:2018-07-26 00:08:45
【问题描述】:

在编写以下 redux-observable 史诗时,我找不到处理 Promise 拒绝的方法。我该如何处理getDataFromPromise 拒绝?我尝试过 pipe、catch、catchError 等。

(action$, store) =>
  action$
    .ofType(request().type)
    .mergeMap(action =>
      fromPromise(getDataFromPromise(action.payload)).map(data =>
        success(data)
      )
    )

按照this 示例,以下应该可以工作,但事实并非如此。

(action$, store) =>
   action$.ofType(request().type).mergeMap(action =>
     fromPromise(getDataFromPromise(action.payload))
       .pipe(catchError(error => of(failure(error))))
       .map(data => success(data))
   )

【问题讨论】:

  • 您可能需要提供 getDataFromPromise 的代码,我不确定 promise 是否拒绝
  • 你可能会想new Promise((resolve,reject)=> reject())。当 promise 解决时,没问题,它可以工作,但是捕获,我无法弄清楚。

标签: rxjs rxjs5 redux-observable


【解决方案1】:

如果您使用的是 RxJS v6,则没有这样的 'fromPromise' observable 创建。请参阅本帖并由 Ben Lesh 回答: https://github.com/ReactiveX/rxjs/issues/3525

相反,您应该使用 'from' 创建 observable。

另外,我建议快速看一下 redux-observable 文档的示例,该文档揭示了使用 'ajax' 助手来处理带有 catchError 运算符的 promise 的 observable 错误: https://redux-observable.js.org/docs/recipes/ErrorHandling.html?_sm_au_=isVnQCj8r4v4Z08F

import { ajax } from 'rxjs/ajax';

const fetchUserEpic = action$ => action$.pipe(
  ofType(FETCH_USER),
  mergeMap(action => ajax.getJSON(`/api/users/${action.payload}`).pipe(
    map(response => fetchUserFulfilled(response))
    catchError(error => of({
      type: FETCH_USER_REJECTED,
      payload: error.xhr.response,
      error: true
    }))
  ))
);

因此,修复代码的更简单方法可能只是遵循这一点并使用“ajax”来包装您的 getDataFromPromise 函数。

【讨论】:

  • 我用的是rxjs5.5,所以不能用。关于请求,它不是 ajax,它的一些处理可能会失败。
猜你喜欢
  • 2018-08-26
  • 2021-06-06
  • 2016-11-10
  • 1970-01-01
  • 2015-04-26
  • 2017-04-23
  • 2022-01-18
  • 2017-07-12
  • 1970-01-01
相关资源
最近更新 更多