Promise 构造函数是同步执行还是异步执行,那么 then 方法呢 ?
参考回答
- Promise 构造函数:
Promise构造函数是同步执行的。它会在创建Promise实例时立即执行传入的执行函数(executor)。即使在executor中有异步操作,它也会在事件循环的当前宏任务中同步执行。new Promise((resolve, reject) => { console.log('executor'); // 这是同步执行的 resolve('resolved'); }); - 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
详细讲解与拓展
- Promise 构造函数的同步执行:
Promise的构造函数中的执行函数(executor)在Promise被创建时立即执行,因此它是同步的。这意味着当你创建一个新的Promise对象时,传递给executor的代码会在当前的调用栈中同步执行完毕。即使executor内部存在异步代码(如setTimeout、setInterval或其他异步操作),这些异步操作的触发依然是在当前宏任务完成后才开始的。new Promise((resolve, reject) => { console.log("Inside executor"); resolve(); }); console.log("Outside executor");输出:
Inside executor Outside executor - 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的回调会被放入微任务队列,待当前宏任务执行完成后才会被执行。