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

参考回答

  1. Promise 构造函数Promise 构造函数是同步执行的。它会在创建 Promise 实例时立即执行传入的执行函数(executor)。即使在 executor 中有异步操作,它也会在事件循环的当前宏任务中同步执行。
    new Promise((resolve, reject) => {
     console.log('executor');  // 这是同步执行的
     resolve('resolved');
    });
    
  2. then 方法then 方法是异步执行的。then 中的回调函数会被放到微任务队列中,待当前宏任务执行完毕后,微任务队列中的任务才会依次执行。
    const promise = new Promise((resolve, reject) => {
     console.log('executor');
     resolve('resolved');
    });
    
    promise.then((value) => {
     console.log('then callback');  // 这是异步执行的
    });
    
    console.log('synchronous code');  // 这是同步执行的
    

    输出顺序:

    executor
    synchronous code
    then callback
    

详细讲解与拓展

  1. Promise 构造函数的同步执行
    Promise 的构造函数中的执行函数(executor)在 Promise 被创建时立即执行,因此它是同步的。这意味着当你创建一个新的 Promise 对象时,传递给 executor 的代码会在当前的调用栈中同步执行完毕。即使 executor 内部存在异步代码(如 setTimeoutsetInterval 或其他异步操作),这些异步操作的触发依然是在当前宏任务完成后才开始的。

    new Promise((resolve, reject) => {
     console.log("Inside executor");
     resolve();
    });
    console.log("Outside executor");
    

    输出:

    Inside executor
    Outside executor
    
  2. then 方法的异步执行
    Promise.then() 方法的回调函数是异步执行的。即使它在 resolve() 被调用后立即被链式调用,then 的回调会被推入微任务队列中。JavaScript 的事件循环机制会先处理当前执行栈中的所有同步任务,然后再处理微任务队列中的任务。

    const promise = new Promise((resolve, reject) => {
     resolve('Resolved!');
    });
    
    promise.then((result) => {
     console.log(result);  // 异步执行
    });
    
    console.log('This is synchronous');  // 同步执行
    

    输出:

    This is synchronous
    Resolved!
    

总结

  • Promise 构造函数:同步执行,在创建时立即执行传入的 executor 函数。
  • then 方法:异步执行,then 的回调会被放入微任务队列,待当前宏任务执行完成后才会被执行。

发表评论

后才能评论