当我们在 promise 中有回调时,执行顺序是什么?



我是JavaScript的新手,不明白为什么会输出以下代码:-

let promise = new Promise((res, rej) => {
setTimeout(() => {
console.log("promise executed");
}, 10000);
res("async executed");
});
console.log("sync programming in progress");
promise
.then((res) => {
console.log(res);
})
.catch((err) => console.log("unexpected error"));
console.log("sync program done");

是:-

sync programming in progress
sync program done
async executed
promise executed

而不是:-

sync programming in progress
sync program done
promise executed
async executed

此外,console.log("async executed"(不会延迟10秒,而是在两个同步console.log 之后立即执行

如@trincot所评论,setTimeout是一个立即返回的函数,在它下面将继续执行,就像任何其他函数调用一样。稍后执行的是给setTimeout的回调,而不是setTimeout调用下面的代码。

最新更新