
Promise 构造函数中的同步执行器(executor)内部发生的异常会被 Promise 机制捕获并处理,将 Promise 的状态置为 rejected,但不会立即中断后续代码的执行。这是因为 Promise 内部对 executor 的调用进行了异常处理,即使 executor 抛出错误,Promise 构造函数仍然会返回一个 rejected 状态的 Promise 对象,允许后续代码继续执行。
在 JavaScript 中,Promise 构造函数提供了一种处理异步操作的方式。一个常见的疑问是,当 Promise 构造函数的执行器(executor)中发生异常时,为什么脚本的其余部分仍然会继续执行,而不是像预期的那样立即停止? 理解这一行为的关键在于 Promise 内部的异常处理机制。
Promise 构造函数接受一个执行器函数作为参数,该函数会在 Promise 创建时同步执行。如果在执行器函数中抛出一个异常,Promise 内部会捕获这个异常,并将 Promise 的状态设置为 rejected。
让我们通过一个例子来说明:
console.log('first');
const promise1 = new Promise((resolve, reject) => {
console.log('inside executor');
let what = 1
console.log(what());
console.log('not reached');
resolve('Hi Guys!');
});
console.log('continues');这段代码的输出如下:
first inside executor continues Uncaught (in promise) TypeError: what is not a function at <anonymous>:5:15
可以看到,尽管在 Promise 的执行器函数中 what() 抛出了一个 TypeError,但 console.log('continues') 仍然被执行了。 这是因为 Promise 内部捕获了该异常,并将其作为 rejection 的原因,但并没有阻止后续代码的执行。
ECMAScript 规范中对 Promise 构造函数的定义解释了这一行为。 简而言之,当执行器函数抛出异常时,Promise 内部会调用 reject 函数,并将异常作为 rejection 的原因。 然而,这个过程并不会中断 Promise 构造函数的执行,而是继续返回一个 rejected 状态的 Promise 对象。
以下是简化的内部 Promise 构造函数的可能实现:
class MyPromise {
#state;
#resolvedValue;
#customers;
constructor(executor) {
this.#state = "pending";
this.#customers = [];
try {
executor(
(value) => this.#resolve(value),
(reason) => this.#reject(reason)
);
} catch(err) {
// 捕获异常,允许执行继续
this.#reject(err);
}
}
#reject(reason) {
if (this.#state !== "pending") return;
this.#state = "rejected";
this.#resolvedValue = reason;
this.#broadcast(); // 触发 then/catch 回调
}
// ... 其他方法
}在上述代码中,try...catch 块捕获了执行器函数中可能抛出的任何异常,并通过 #reject 方法将 Promise 的状态设置为 rejected。 关键在于,catch 块吸收了错误,并允许执行继续。
理解 Promise 的异常处理机制对于编写健壮的异步代码至关重要。 通过显式地处理 Promise 的 rejection,可以避免潜在的错误,并确保程序的正确执行。
以上就是Promise 构造函数中的异常为何不会阻止脚本的其余部分执行?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号