promise和setTimeout的执行顺序问题?

为什么这段代码输出是先2后1呢?

const promise = new Promise(function (resolve) {
    setTimeout(function () {
        resolve(1);
        console.log("2");
    });
})
promise.then(function (res) {
    console.log(res);
});
阅读 1.3k
1 个回答

1、执行new Promise,执行setTimeout,将里面代码加入宏任务
2、执行promise.then,promise状态还未改变,所以还没把then回调加入微任务
3、执行setTimeout代码,执行resolve(1),把then回调加入微任务,执行console.log("2");,打印2
4、执行console.log(res);,打印1

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题