MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

Promise.prototype.catch()

catch() 方法只處理 Promise 的 rejected 狀態,並回傳一個新的 Promise 物件。此方法的行為等同於呼叫 Promise.prototype.then(undefined, onRejected)

語法

p.catch(onRejected);

p.catch(function(reason) {
   // rejection
});

參數

onRejected
當 Promise 被拒絕時,會被呼叫的 Function ,同時他會傳入一個引數。
reason
被拒絕的原因。
如果 onRejected 拋出一個錯誤或是從中回傳一個已經被拒絕的 Promise,catch() 會回傳那個已經被拒絕的 Promise。否則,catch() 回傳狀態為 resolved 的 Promise。

回傳值

Promise

描述

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

規範

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Promise.prototype.catch' in that specification.
Standard Initial definition in an ECMA standard.
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Promise.prototype.catch' in that specification.
Draft  

相覽器相容性

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

參見

文件標籤與貢獻者

 此頁面的貢獻者: Calvin-Huang, liuderchi, jackblackevo
 最近更新: Calvin-Huang,