Mos*_*she 6 javascript request promise
我将一个request-promise-native调用包装在一个返回承诺的函数中。
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如果我将of中的 return 语句更改为requestWrapper:
.catch(err => err)
甚至这个:
.catch(err => Promise.resolve(err))
要返回 a ,我按照预期得到了调用的错误resolve堆栈。thenrequestWrapper
节点喊道:
(node:24260) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): ...
好的,感谢@pathurs 和@Hendry,我得到了我需要的东西。
首先,正确的方法是 @Hendry 建议的,即不要在包装器中处理 catch,而是在函数调用中处理。这就是我走过的路:
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
| 归档时间: | 
 | 
| 查看次数: | 7313 次 | 
| 最近记录: |