承诺捕获行为 [英] Promise catch behavior
本文介绍了承诺捕获行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
似乎可以正常运行,而不会抛出错误:
it seems the following works without throwing an error:
var p = new Promise (function (resolve, reject) {
window.setTimeout(function() {
reject('ko');
}, 1000);
});
p.then(function (value) { console.log(value); })
.catch(function () { console.log('catched'); });
// → 'catched'
但这会引发错误:
var p = new Promise (function (resolve, reject) {
window.setTimeout(function() {
p.catch(function () { console.log('catched'); });
reject('ko');
}, 1000);
});
p.then(function (value) { console.log(value); });
// → 'catched'
// Uncaught (in promise) ko
任何疯狂的猜测为何?
推荐答案
.catch
必须直接链接在.then
之后.即使以这种方式编写,它仍然会报告未捕获的内容:
The .catch
must be directly chained after .then
. Even if you write it this way, it will still report uncaught:
var p = new Promise(function(resolve, reject) {
window.setTimeout(function() {
//p.catch(function () { console.log('catched'); });
console.log(p)
reject('ko');
}, 1000);
});
p.then(function(value) {
console.log(value);
});
p.catch(function() {
console.log('catched');
});
这样做的原因是,如果不这样链接它,则.catch
函数将不会收到调用.then
The reason for this is that if you don't chain it like that, the .catch
function doesn't receive the return value that gets generated when you call .then
这篇关于承诺捕获行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文