Promise 构造函数的执行
同步执行:
Promise
的构造函数(即new Promise(executor)
)是同步执行的。- 当你创建一个新的
Promise
实例时,传递给构造函数的executor
函数会立即同步执行。 - 在
executor
函数中调用resolve
或reject
也是同步的,直到executor
函数执行完毕,Promise
的状态才会改变。
示例:
console.log("Start");
const promise = new Promise((resolve, reject) => {
console.log("Inside promise executor");
resolve("Resolved value");
});
console.log("After promise creation");
promise.then((value) => {
console.log("Inside then");
console.log(value);
});
console.log("End");
输出:
Start
Inside promise executor
After promise creation
End
Inside then
Resolved value
then
方法的执行
异步执行:
then
方法的回调函数(onFulfilled
和onRejected
)是异步执行的。它们会在当前执行栈清空后被执行,即微任务队列(Microtask Queue)中。- 当
Promise
的状态变为fulfilled
或rejected
时,then
方法中注册的回调函数会被加入微任务队列,在当前脚本执行完后,事件循环会处理这些微任务。
示例:
console.log("Start");
const promise = new Promise((resolve, reject) => {
console.log("Inside promise executor");
resolve("Resolved value");
});
console.log("After promise creation");
promise.then((value) => {
console.log("Inside then");
console.log(value);
});
console.log("End");
输出:
Start
Inside promise executor
After promise creation
End
Inside then
Resolved value