zxdfe / FE-Interview

Every step counts
34 stars 1 forks source link

第71题:Promise 构造函数是同步执行还是异步执行,那么 then 方法呢? #72

Open zxdfe opened 1 year ago

zxdfe commented 1 year ago

说出下列代码执行结果,并解释原因

const promise = new Promise((resolve, reject) => {
  console.log(1);
  resolve(5);
  console.log(2);
}).then(val => {
  console.log(val);
});

promise.then(() => {
  console.log(3);
});

console.log(4);

setTimeout(function() {
  console.log(6);
});
Moooodena commented 1 year ago

Promise 构造函数是同步执行,.then是异步 1 2 4 5 3 6

zicuan123 commented 1 year ago

promise属于同步任务,promise.then属于微任务,setTimeout属于宏任务 第一轮整个script作为宏任务执行:执行了所有同步任务,并将所有微任务放入微任务队列,宏任务放入宏任务队列,所以第一轮打印了1,2,4 宏任务执行完后,检查微任务队列,执行所有微任务,打印了5,3 微任务执行完,取出一个宏任务执行,打印了6 所以最终打印结果为:1,2,4,5,3,6

2734209032 commented 1 year ago

1,2,4,5,3,6 promise构造函数本身是同步代码,.then里面的回调函数时微任务,异步的