承诺:那么vs那么+赶上 [英] Promise : then vs then + catch
本文介绍了承诺:那么vs那么+赶上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下两个代码之间是否有任何区别?
Is there any difference between the 2 followings codes ?
myPromise.then(function() {
console.log('success');
}).catch(function() {
console.log('error');
});
myPromise.then(function() {
console.log('success');
}, function() {
console.log('error');
});
我知道然后
和 catch
使用回调中的值返回返回已解决或拒绝的新promise。但是我看到了网络上的2个代码,我很好奇两个代码之间的真正区别。
I know then
and catch
returns new promises resolved or rejected with the value returns in the callback. But i see the 2 codes around the web and i'm curious about the real differences between the 2 codes.
推荐答案
在你的当前代码,它们的行为相同,因为 console.log('success');
不会失败。
In your current code, they act the same because console.log('success');
will not fail.
但是,如果你写这样的东西......
However, if you write something like this...
myPromise.then(function() {
// Some error may happen
throw('An exception that would be caught');
}).catch(function() {
console.log('error');
});
// Is the same as this, the errHandle tries to catch any unhandled error
// from previous result.
myPromise.then(func, null).then(null, errHandle);
myPromise.then(function() {
// Some error may happen
throw('An unhandled exception.');
}, function() {
// This won't log the error if it happens in the
// some error may happen block.
console.log('error');
});
// Is the same as this, the errHandle will handle errors from previous result,
// but it won't handle errs in func.
myPromise.then(func, errHandle)
第二种形式无法捕捉到该错误,第一个可以。
The second form can't catch that error, while the first can.
测试片段:
Snippet for test:
// An function that may error and throw exception.
function funcThatThrows(test) {
throw(`oops - error in test ${test}`);
}
function errHandler(exception) {
console.log('We got an exception: ', exception);
}
// Expect: We got an exception: oops - error in test 1
Promise.resolve(1).then(funcThatThrows).catch(errHandler);
// Is the same as below, the errHandler tries to catch any unhandled error
// from previous result.
// Expect: We got an exception: oops - error in test 2
Promise.resolve(2).then(funcThatThrows, null).then(null, errHandler);
// If put the function and handler in the same then, the exception won't be caught.
// Expect: Uncaught (in promise) oops - error in test 3
Promise.resolve(3).then(funcThatThrows, errHandler);
这篇关于承诺:那么vs那么+赶上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文