承诺:那么vs那么+赶上

时间:2015-10-22 09:58:42

标签: javascript promise

以下2个代码有什么区别吗?

myPromise.then(function() {
    console.log('success');
}).catch(function() {
    console.log('error');
});

myPromise.then(function() {
    console.log('success');
}, function() {
    console.log('error');
});

我知道thencatch使用回调中的值返回来返回已解决或拒绝的新承诺。但我看到了网络上的2个代码,我对2个代码之间的真正差异感到好奇。

2 个答案:

答案 0 :(得分:121)

在您当前的代码中,它们的行为相同,因为}不会失败。

但是,如果你写这样的东西......

console.log('success');

第二种形式无法捕获该错误,而第一种形式可以。

测试片段:



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)




答案 1 :(得分:-1)

我猜这取决于Promise的实施方式。 据我所知,jQuery在different fashion中实现它。

你给的第二个似乎是jQuery版本。

相关问题