catch() 方法返回一个Promise,并且处理拒绝的情况。它的行为与调用Promise.prototype.then(undefined, onRejected)
相同。 (事实上, calling obj.catch(onRejected)
内部calls obj.then(undefined, onRejected)
).
语法
p.catch(onRejected); p.catch(function(reason) { // 拒绝 });
参数
- onRejected
-
当Promise 被rejected时,被调用的一个
Function
。 该函数拥有一个参数: -
reason
rejection 的原因。 -
如果
onRejected
抛出一个错误或返回一个本身失败的 Promise , 通过catch()
返回的Promise 被rejected;否则,它将显示为成功(resolved)。返回值
一个
Promise
.
描述
catch
方法可以用于您的promise组合中的错误处理。
Internally calls Promise.prototype.then
on the object upon which is called, passing the parameters undefined
and the onRejected
handler received; then returns the value of that call (which is a Promise
).
示例
使用链式语句的 catch
方法
var p1 = new Promise(function(resolve, reject) {
resolve('Success');
});
p1.then(function(value) {
console.log(value); // "Success!"
throw 'oh, no!';
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
// 以下行为与上述相同
p1.then(function(value) {
console.log(value); // "Success!"
return Promise.reject('oh, no!');
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
捕获抛出的错误
// 抛出一个错误,大多数时候将调用catch方法
var p1 = new Promise(function(resolve, reject) {
throw 'Uh-oh!';
});
p1.catch(function(e) {
console.log(e); // "Uh-oh!"
});
// 在异步函数中抛出的错误不会被catch捕获到
var p2 = new Promise(function(resolve, reject) {
setTimeout(function() {
throw 'Uncaught Exception!';
}, 1000);
});
p2.catch(function(e) {
console.log(e); // 不会执行
});
// 在resolve()后面抛出的错误会被忽略
var p3 = new Promise(function(resolve, reject) {
resolve();
throw 'Silenced Exception!';
});
p3.catch(function(e) {
console.log(e); // 不会执行
});
如果已决议
//创建一个新的 Promise ,且已决议
var p1 = Promise.resolve("calling next");
var p2 = p1.catch(function (reason) {
//这个方法永远不会调用
console.log("catch p1!");
console.log(reason);
});
p2.then(function (value) {
console.log("next promise's onFulfilled"); /* next promise's onFulfilled */
console.log(value); /* calling next */
}, function (reason) {
console.log("next promise's onRejected");
console.log(reason);
});
规范
规范 | 状态 | 备注 |
---|---|---|
domenic/promises-unwrapping | Standard | Initial definition in an ECMA standard. |
ECMAScript 2015 (6th Edition, ECMA-262) Promise.prototype.catch |
Standard |
浏览器兼容性
No compatibility data found. Please contribute data for "javascript/promise" (depth: Promise.prototype.catch) to the MDN compatibility data repository.