Promise : then vs then + catch
Promise : then vs then + catch
以下两个代码有什么区别吗?
myPromise.then(function() {
console.log('success');
}).catch(function() {
console.log('error');
});
myPromise.then(function() {
console.log('success');
}, function() {
console.log('error');
});
我知道then
和catch
返回新的承诺解决或拒绝的值在回调中返回。但是我在网上看到了这两个代码,我很好奇这两个代码之间的真正区别。
在您当前的代码中,它们的行为相同,因为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)
第二种形式不能捕获这个错误,而第一种形式可以。
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);
相关文章:
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- Javascript:If-then语句在函数中不起作用
- angularjs无法读取未定义的属性then
- errors with Javascript try catch
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- Promise函数在.then之后未运行函数化
- Javascript 承诺 .catch 仍然调用 final variable.then
- 为什么 JavaScript Promise 有时既不使用 .catch 也不使用 .then
- 在 AngularJS 中使用 then 和 catch 时出错
- 与茉莉花中 ES6 承诺的 then/catch 方法同步
- Factory - Then and Catch Promise Chaining in AngularJS
- Promise : then vs then + catch
- Jasmin Mock $http (then, catch)
- 如何从Promise's catch/then block返回
- 获取api - get json主体在then和catch块为单独的状态码
- 答应立刻处理.catch和.then
- javascript try catch vs if then else
- 如何测试' catch '和' then '与sinon js
- 有没有办法回报对.catch和.then的承诺
- 即使我在所有 then-able 中使用拒绝回调,我是否总是需要在最后需要 catch()