Xử lý ngoại lệ riêng biệt trong Promise trong JavaScript
Trong then, bạn chỉ có thể chỉ định một hàm xử lý
tình huống ngoại lệ bằng cách truyền null thay cho tham số
đầu tiên:
promise.then(
null,
function(error) {
console.log(error);
}
);
Trong trường hợp như vậy, sẽ thuận tiện khi sử dụng cú pháp
rút gọn thông qua phương thức catch:
promise.catch(
function(error) {
console.log(error);
}
);
Hãy viết lại đoạn mã sau bằng phương thức catch:
let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
let isError = false;
if (!isError) {
resolve('success');
} else {
reject(new Error('error'));
}
}, 3000);
});
promise.then(
res => console.log(res),
err => console.log(err.message),
);