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
});

规范

规范 状态 备注
domenic/promises-unwrapping Standard Initial definition in an ECMA standard.
ECMAScript 2015 (6th Edition, ECMA-262)
Promise.prototype.catch
Standard  

浏览器兼容性

Feature Chrome Edge Firefox Internet Explorer Opera Safari Servo
Basic Support32.0(Yes)29.0No support197.1No support
Feature Android Chrome for Android Edge Mobile Firefox for Android IE Mobile Opera Mobile Safari Mobile
Basic Support4.4.432.0(Yes)29No support(Yes)8.0

相关链接

文档标签和贡献者

 此页面的贡献者: Yevvb, HsuanLee, xgqfrms-GitHub, Hushabyme, fskuok, mountainmoon
 最后编辑者: Yevvb,