需求 在promise中的某一步骤发生错误的时候,终止往下执行并跳出promise。
关键点 throw、catch
代码 根据promise的原理可知,promise传入的函数是会完全执行的,resolve和reject函数只是将执行的结果给保存了下来,保存为onResolve和onReject所需要使用的参数值,后续仍然会去继续执行then函数注册的onResolve和onReject方法。所以reject后的代码仍然会执行,而通过throw指令会中止掉该函数的执行,将执行权交还。所以5不会输出
var a = function () {
return new Promise((resolve, reject) => {
reject(1);
console.log(2);
}).catch((e) => {
console.log(e);
throw 3;
});
};
var b = async function () {
await a().catch((e) => {
console.log(e);
throw 4;
});
console.log(5);
};
(async () => {
await b().catch((e) => {
console.log(e);
});
})();
// 2
// 1
// 3
// 4