1. 一般总是建议,Promise 对象后面要跟catch
方法,这样可以处理 Promise 内部发生的错误。
catch
方法返回的还是一个 Promise 对象,因此后面还可以接着调用then
方法。
const p1 =new Promise((resolve, reject) => { resolve(x+2); // 会报错,因为x没有声明 }); p1.catch((err) => { console.log(‘oh no‘, err); // catch 返回一个resolved promise对象 }).then(() => { console.log(‘carry on‘); }); // oh no ReferenceError: x is not defined // carry on
catch方法中,还能再抛出错误。
const someAsyncThing = function() { return new Promise(function(resolve, reject) { // 下面一行会报错,因为x没有声明 resolve(x + 2); }); }; someAsyncThing().then(function() { return someOtherAsyncThing(); }).catch(function(error) { console.log(‘oh no‘, error); // 下面一行会报错,因为 y 没有声明 y + 2; }).then(function() { console.log(‘carry on‘); //没有执行,因为catch中返回的是一个reject的promise }); // oh no [ReferenceError: x is not defined]
catch
方法抛出一个错误,因为后面没有别的catch
方法了,导致这个错误不会被捕获,也不会传递到外层。
2. promise.all
let p3 = new Promise((resolve, reject) => { resolve(‘hello‘); }) .then(result => result) .catch(e => e); let p4 = new Promise((resolve, reject) => { throw new Error(‘报错了‘); }) .then(result => result) .catch(e => e); Promise.all([p3, p4]) .then(result => console.log(‘hi‘)) .catch(e => console.log(e)); // hi ["hello", Error: 报错了 at <anonymous>:8:9 at new Promise (<anonymous>) at <anonymous>:7:10]
原文:https://www.cnblogs.com/ceceliahappycoding/p/11382268.html