Promise : then vs then + catch
本问题已经有最佳答案,请猛点这里访问。
以下2个代码有什么区别吗?
1 2 3 4 5 6 7 8 9 10 11 | myPromise.then(function() { console.log('success'); }).catch(function() { console.log('error'); }); myPromise.then(function() { console.log('success'); }, function() { console.log('error'); }); |
我知道
在您当前的代码中,它们的行为相同,因为
但是,如果你写这样的东西......
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // 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); |
我猜它取决于Promise的实现方式。
据我所知,jQuery以不同的方式实现它。
你给的第二个似乎是jQuery版本。