[英]Why does using catch on Promise.reject() changes it to a fulfilled promise?
[英]How to .catch a Promise.reject
我有一个辅助函数,用于在 CouchDB 中使用fetch
,其结尾为:
...
return fetch(...)
.then(resp => resp.ok ? resp.json() : Promise.reject(resp))
.then(json => json.error ? Promise.reject(json) : json)
当我在其他地方使用它时,我的印象是我可以.catch
那些明确的拒绝:
above_function(its_options)
.then(do_something)
.catch(err => do_something_with_the_json_error_rejection_or_resp_not_ok_rejection_or_the_above(err))
但唉,我似乎无法控制拒绝。 我遇到的具体错误是 HTTP 401 响应。
什么给?
(请注意,有隐含的ES6 return
的中.then
S)
function test() { return new Promise((resolve, reject) => { return reject('rejected') }) } test().then(function() { //here when you resolve }) .catch(function(rej) { //here when you reject the promise console.log(rej); });
确保每次调用then()
返回一个值。
例如
var url = 'https://www.google.co.in'; var options = {}; var resolves = Promise.resolve(); resolves.then(() => { console.log('Resolved first promise'); var fetchPromise = fetch(url, options); fetchPromise.then(() => { console.log('Completed fetch'); }); }) .catch(error => { console.log('Error', error); });
请注意console
显示未捕获的异常。 但是,如果您返回了内部承诺(或任何其他值,最终通过resolve
变成了承诺),您最终会扁平化承诺,因此异常冒泡。
var url = 'https://www.google.co.in'; var options = {}; var resolves = Promise.resolve(); resolves.then(() => { console.log('Resolved first promise'); var fetchPromise = fetch(url, options); return fetchPromise.then(() => { console.log('Completed fetch'); }); }) .catch(error => { console.log('Error', error); });
注意异常冒泡到外部承诺。 希望这可以使事情稍微澄清一些。
为什么不将它包装在try / catch
块中,我已经从ivo 中复制了以下内容
function test() {
return new Promise((resolve, reject) => {
return reject('rejected');
})};
(async ()=>{
try{
await test()
}catch(er){
console.log(er)
}})();
Promise 拒绝属于then
函数的第二个参数。
function test() {
return new Promise((resolve, reject) => {
return reject('rejected')
})
}
test().then(function() {
//here when you resolve
}, function(rej) {
//here when you reject the promise
console.log(rej)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.