Skip to content

Promise 构造函数是同步执行还是异步执行,那么 then 方法呢?

Posted on:2024年8月14日 at 23:41

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 方法的执行

异步执行

示例

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
原文转自:https://fe.ecool.fun/topic/1bdd3e29-f9b2-4f1d-a8b2-6a8b14320779