总结:
Promise 链式调用中一个环节报错,后续的 then 方法默认不会执行,但可通过 catch 方法恢复链式调用的执行。
案例:
asyncOperation2报错后,第二个then不会执行,后续也不会执行,直接到最近的catch里
function asyncOperation1() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('操作 1 成功');
}, 1000);
});
}
function asyncOperation2() {
return new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('操作 2 失败'));
}, 1000);
});
}
function asyncOperation3() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('操作 3 成功');
}, 1000);
});
}
asyncOperation1()
.then(result => {
console.log(result);
return asyncOperation2();
})
.then(result => {
// 由于 asyncOperation2 报错,此 then 不会执行
console.log(result);
return asyncOperation3();
})
.catch(error => {
console.error('捕获到错误:', error.message);
});
在catch里恢复resolve后,后续then会继续执行
function asyncOperation1() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('操作 1 成功');
}, 1000);
});
}
function asyncOperation2() {
return new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('操作 2 失败'));
}, 1000);
});
}
function asyncOperation3() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('操作 3 成功');
}, 1000);
});
}
asyncOperation1()
.then(result => {
console.log(result);
return asyncOperation2();
})
.then(result => {
console.log(result);
return asyncOperation3();
})
.catch(error => {
console.error('捕获到错误:', error.message);
// 返回一个新的已解决的 Promise
return Promise.resolve('从错误中恢复');
})
.then(result => {
console.log('继续执行:', result);
});