JavaScript:Promise 回调执行



我需要知道Promise是同步执行还是异步执行。根据 Mozilla 文档,promise回调 - executor 函数由Promise实现立即执行。

但根据以下代码,它对我来说似乎不是这样工作的——

let myPromise = new Promise((resolve, reject) =>
resolve("Resolved from the promise");
);
myPromise.then(console.log);
console.log("After resolving the promise");

promisethen处理程序中的日志在最后一行的日志之后打印。为什么它像异步方式一样执行。我错过了什么吗?

promise 执行器函数是你传递给new Promise的函数。它是同步执行的,因此它可以启动承诺所代表的任何异步进程。

您附加的thencatchfinally的回调始终是异步调用的,无论承诺是否已解决。

因此,在您的示例中,在您传递给thenconsole.log之前调用console.log("After resolving the promise");

下面是一个更清楚地说明这一点的示例:

let myPromise = new Promise((resolve, reject) => {
console.log("In the executor function");
resolve("Resolved from the promise");
});
myPromise.then(result => {
console.log("In the fulfillment handler: " + result);
});
console.log("After resolving the promise");

其输出为:

在执行器函数中 解决承诺后 在履行处理程序中

: 从承诺中解析 请注意,"在执行器函数中"记录在"解析承诺之后"之前,因为执行程序是同步调用的,但"在履行处理程序中:从承诺中解析"是之后,因为它是异步调用的。

通过创建承诺,您进入了所谓的微任务领域:不完全在下一个事件循环中执行,但也不是立即执行。使用queueMicrotask功能可以实现同样的事情。考虑:

setTimeout(() => console.log("I'll be printed last"));
Promise.resolve().then(() => console.log("I'll be printed second"));
queueMicrotask(() => console.log("I'll be printed third"));
console.log("I am printed first");

如果将Promise.resolve线与queueMicrotask线交换,则也会交换它们各自的输出。设置的顺序始终是:运行代码完成(立即执行console.log(,运行任何挂起的微任务(第二行和第三行(,转到下一个事件循环tick(在上面的例子中,它被来自setTimeout的函数调用占用(。

延伸阅读: https://javascript.info/event-loop

Promise 的执行器函数始终是同步调用的。

所以,在这行之后,

let myPromise = new Promise((resolve, reject) =>
resolve("Resolved from the promise");
);

承诺将处于已解决状态。

相比之下,使用then添加的回调始终异步调用,即使在添加回调时承诺已处于已结算状态也是如此。

最新更新