Javascript 如何.catch Promise.reject
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46005954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to .catch a Promise.reject
提问by morbusg
I have a helper function for using fetchwith CouchDB which ends as:
我有一个用于fetchCouchDB的辅助函数,其结尾为:
...
return fetch(...)
.then(resp => resp.ok ? resp.json() : Promise.reject(resp))
.then(json => json.error ? Promise.reject(json) : json)
and when I use it elsewhere, I was under the impression that I could .catchthose explicit rejections:
当我在其他地方使用它时,我的印象是我可以.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))
but alas, I can't seem to be able to get a hold of the rejections. The specific error I'm after is a HTTP 401 response.
但唉,我似乎无法控制拒绝。我遇到的具体错误是 HTTP 401 响应。
What gives?
是什么赋予了?
(Please note that there are implicit ES6 return's in the .thens)
(请注意在returns 中有隐含的 ES6 .then)
回答by ivo
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);
});
回答by Rahul
Make sure every call to a then()returns a value.
确保每次调用 a 都then()返回一个值。
For e.g.
例如
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);
});
Notice the consoleshows an uncaught exception. However, if you returned the inner promise (or any other value, which ends up turning into a promise via resolve), you end up flattening the promise so exception bubble up.
请注意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);
});
Notice the exception bubbles up to the outer promise. Hope this clears up things a little bit.
注意异常冒泡到外部承诺。希望这可以使事情稍微澄清一些。
回答by yBrodsky
Promise rejections fall to the second param of the thenfunction.
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)
})

