Promise.prototype.catch方法是.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数。
getJSON(‘/posts.json‘).then(function(posts) {
// ...
}).catch(function(error) {
// 处理 getJSON 和 前一个回调函数运行时发生的错误
console.log(‘发生错误!‘, error);
});
getJSON方法返回一个 Promise 对象,
如果该对象状态变为resolved,则会调用then方法指定的回调函数;
如果异步操作抛出错误,状态就会变为rejected,就会调用catch方法指定的回调函数,处理这个错误
p.then((val) => console.log(‘fulfilled:‘, val))
.catch((err) => console.log(‘rejected‘, err));
// 等同于
p.then((val) => console.log(‘fulfilled:‘, val))
.then(null, (err) => console.log("rejected:", err));
then方法指定的回调函数,如果运行中抛出错误,也会被catch方法捕获。
const promise = new Promise(function(resolve, reject) {
throw new Error(‘test‘);
});
promise.catch(function(error) {
console.log(error);
});
等同于
const promise = new Promise(function(resolve, reject) {
reject(new Error(‘test‘));
});
promise.catch(function(error) {
console.log(error);
});
resolved,再抛出错误是无效的const promise = new Promise(function(resolve, reject) {
resolve(‘ok‘);
throw new Error(‘test‘);
});
promise
.then(function(value) { console.log(value) })
.catch(function(error) { console.log(error) });
// ok
Promise 在resolve语句后面,再抛出错误,不会被捕获,等于没有抛出。
因为 Promise 的状态一旦改变,就永久保持该状态,不会再变了。
Promise 对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个catch语句捕获。
getJSON(‘/post/1.json‘).then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// some code
}).catch(function(error) {
// 处理前面三个Promise产生的错误
});
一共有三个 Promise 对象:一个由getJSON产生,两个由then产生。
它们之中任何一个抛出的错误,都会被最后一个catch捕获。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行会报错,因为x没有声明
resolve(x + 2);
});
};
someAsyncThing().then(function() {
console.log(‘everything is great‘);
});
setTimeout(() => { console.log(123) }, 2000);
// Uncaught (in promise) ReferenceError: x is not defined
// 123
someAsyncThing函数产生的 Promise 对象,内部有语法错误。
浏览器运行到这一行,会打印出错误提示ReferenceError: x is not defined,
但是不会退出进程、终止脚本执行,2 秒之后还是会输出123。
这就是说,Promise 内部的错误不会影响到 Promise 外部的代码,
通俗的说法就是“Promise 会吃掉错误”。
原文:https://www.cnblogs.com/blogZhao/p/12565868.html