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.4k
1 个回答

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

推荐问题