Promise.prototype.catch()

该新特性属于 ECMAScript 2015(ES6)规范,在使用时请注意浏览器兼容性。

概述

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

语法

p.catch(onRejected);

p.catch(function(reason) {
   // 失败
});

参数

onRejected
Promise 失败时,调用 Function 。 该函数拥有一个参数:
reason
失败的原因。

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

描述

catch 方法主要应用于 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');
});

// The following behaves the same as above
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');
});

捕获抛出的错误

// Throwing an error will call the catch method most of the time
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

相关链接

文档标签和贡献者

 此页面的贡献者: Hushabyme, fskuok, mountainmoon
 最后编辑者: Hushabyme,