--- title: Promise.prototype.catch() slug: Web/JavaScript/Reference/Global_Objects/Promise/catch translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch ---
Phương thức catch() trả ra một Promise để xử lý trường hợp xử lý của ta thất bại. Nó cũng giống như {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}} nhưng chỉ được gọi khi thao tác của ta thất bại.
p.catch(onRejected);
p.catch(function(reason) {
// rejection
});
Promise của ta thất bại. Hàm này có một tham số đầu vào là:
reasonMột {{jsxref("Promise")}} mới.
Phương thước catch rất hữu ích cho việc xử lý các lỗi xảy ra trong 1 Promise hoặc một chuỗi Promise có quan hệ thứ tự với nhau (đợi nhau).
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
});
| Đặc tả | Trạng thái | Ghi chú |
|---|---|---|
| {{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}} | {{Spec2('ES6')}} | Initial definition in an ECMA standard. |
| {{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}} | {{Spec2('ESDraft')}} |
To contribute to this compatibility data, please write a pull request against this file: https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json.
{{Compat}}