简体   繁体   English

如何在使用Observable.from(<Promise>)并在Observable中捕获错误时处理`UnhandledPromiseRejectionWarning`

[英]How to handle `UnhandledPromiseRejectionWarning` when using Observable.from(<Promise>) and catching error in the Observable

I am using redux-observable together with isomorphic-fetch to handle http requests in my React app. 我正在使用redux-observableisomorphic-fetch来处理我的React应用程序中的http请求。 I am favouring this combination over using rxjs' ajax because I am testing with Jest - which runs tests in Node.js - and want to intercept http requests with nock . 我偏袒使用rxjs'这个组合ajax ,因为我与测试Jest -它运行试验中Node.js -并希望与拦截HTTP请求nock See this related question: Use fetch instead of ajax with redux-observable . 请参阅此相关问题: 使用fetch而不是带有redux-observable的ajax

So here is the problem: I get an UnhandledPromiseRejectionWarning together with a scary: DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 所以这就是问题:我得到一个UnhandledPromiseRejectionWarning以及一个可怕的: DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. because I am not catching my promise rejections directly but rather leave that to the Observable: 因为我没有直接接受我的承诺拒绝,而是将其留给Observable:

// apiModule.js
import fetch from 'isomorphic-fetch'

const api = {
  getSomething: () => {
    const request = fetch('http://some-api/')
      .then(res => catchError(res)) // throwing an Error here if not response.ok
      .then(res => res.json())

    return Observable.from(request)
  }
}

Then in the epic: 然后在史诗中:

// myReduxModule.js
import {api} from './apiModule.js'

const getSomethingEpic = action$ =>
  action$
    .ofType(GET_SOMETHING)
    .mergeMap(action =>
      api
        .getSomething()
        .map(response => getSomethingSucceeded(response))
        .catch(error => logError(error)) // error is handled here!
    )

So the promise rejection is handled in the Observable but not directly! 因此承诺拒绝在Observable中处理,但不是直接处理!

Any suggestions how to avoid the warning (and a possible future terminate with non-zero exit code) in this scenario? 在这种情况下,如何避免警告(以及可能的未来以非零退出代码终止)的任何建议?

From now on, every time you have a promise and you call the then , you must also implement the catch . 从现在开始,每当你有一个承诺并且你打电话给那个then ,你也必须实现catch Also in your tests. 也在你的测试中。

 const request = fetch('http://some-api/')
      .then(res => catchError(res))
      .then(res => res.json())
      .catch(err => catchError(res)) // <= here you should implement the catch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM