我包裹了一个 request-promise-native
调用返回 promise 的函数。
import request from 'request-promise-native';
function requestWrapper(url) {
return request(url)
.then(data => {...})
.catch(err => Promise.reject(err));
}
简单吧?
现在我正在使用这个功能,
then
工作正常,但 catch
永远抓不到Promise.reject
:requestWrapper('http://some-url.com')
.then(data => {...})
.catch(err => console.log(err));
我从来没有接到电话的
catch
!如果我更改
catch
中的返回语句的 requestWrapper
对此:.catch(err => err)
甚至这个:
.catch(err => Promise.resolve(err))
返回
resolve
,我在 then
上得到错误堆栈的requestWrapper
像预期的那样打电话。节点喊道:
(node:24260) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): ...
最佳答案
好的,感谢@pathurs 和@Hendry,我得到了我需要的东西。
首先,正确的方法是@Hendry 建议的,即不在包装器中处理捕获,而是在函数调用中处理。这就是我去的方式:
function requestWrapper(url) {
return request(url)
.then(data => {...})
}
requestWrapper('http://some-url.com')
.then(data => {...})
.catch(err => console.log(err));
伟大的!
但显然,@pathurs 方式也有效:
function requestWrapper(url) {
return request(url)
.then(data => {...})
.catch(err => Promise.reject(err));
}
requestWrapper('http://some-url.com')
.then(data => {...}, err => console.log(err));
我不明白这是原生功能,还是
request
的一些附加功能图书馆:https://github.com/request/request-promise#thenonfulfilled-onrejected
关于javascript - 即使我确实处理了未处理的 promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48398094/