The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.prototype.then(undefined, onRejected).
p.catch(onRejected);
p.catch(function(reason) {
// rejection
});
Function called when the Promise is rejected. This function has one argument: reasoncatch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.A Promise.
The catch method can be useful for error handling in your promise composition.
catch methodvar 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 Support | 32.0 | (Yes) | 29.0 | No support | 19 | 7.1 | No support |
| Feature | Android | Chrome for Android | Edge Mobile | Firefox for Android | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|---|
| Basic Support | 4.4.4 | 32.0 | (Yes) | 29 | No support | (Yes) | 8.0 |
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch