Promise.prototype.catch()

catch() 方法返回一个Promise,只处理拒绝的情况。它的行为与调用Promise.prototype.then(undefined, onRejected) 相同。

语法

p.catch(onRejected);

p.catch(function(reason) {
   // 拒绝
});

参数

onRejected
当Promise 被拒绝时,被调用的一个Function。 该函数拥有一个参数:
reason
拒绝的原因。

 如果 onRejected 抛出一个错误或返回一个失败的 Promise ,Promise  通过 catch() 返回失败结果;否则,它将显示为成功。 

返回值

一个Promise.

描述

catch 方法可以用于您的promise组合中的错误处理。

示例

使用链式语句的 catch方法

var p1 = new Promise(function(resolve, reject) {
  resolve('Success');
});

p1.then(function(value) {
  console.log(value); // "成功!"
  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); // "成功!"
  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!"
});

// Errors thrown inside asynchronous functions will act like uncaught errors
var p2 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    throw 'Uncaught Exception!';
  }, 1000);
});

p2.catch(function(e) {
  console.log(e); // This is never called
});

// Errors thrown after resolve is called will be silenced
var p3 = new Promise(function(resolve, reject) {
  resolve();
  throw 'Silenced Exception!';
});

p3.catch(function(e) {
   console.log(e); // This is never called
});

如果已决议

//创建一个新的 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" to the MDN compatibility data repository.

相关链接

文档标签和贡献者

 最后编辑者: zhishaofei3,