JavaScript: Promise回调执行

JavaScript: Promise callback execution

我需要知道 Promise 是同步执行还是异步执行。根据 mozilla docspromise 回调 - 执行器函数由 Promise 实现立即执行。

但根据下面的代码,它对我来说似乎并不像那样工作-

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

myPromise.then(console.log);

console.log("After resolving the promise");

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

promise 执行器函数是您传递给 new Promise 的函数。它是同步执行的,因此它可以启动 promise 表示的任何异步过程。

您使用 thencatchfinally 附加的回调 总是 异步调用,无论 promise 是否已经结算或没有。

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

这是一个更清楚地说明这一点的例子:

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");

其输出为:

In the executor function
After resolving the promise
In the fulfillment handler: Resolved from the promise

请注意,"In the executor function" 在 "After resolving the promise" 之前记录,因为执行程序是同步调用的,但 "In the fulfillment handler: Resolved from the promise" 在之后,因为它是异步调用的。

Promise 的执行器函数总是被同步调用。

所以,在这一行之后,

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

承诺将处于已解决状态。

相比之下,使用 then 添加的回调始终被异步调用,即使在添加回调时 promise 已经处于稳定状态。

通过创建承诺,您进入了所谓的 microtask 领域:不完全在下一个事件循环滴答中执行,但也不是立即执行。使用 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),运行 任何待处理的微任务(第二和第三行),转到下一个事件循环滴答(在上面的示例中,它被来自 setTimeout 的函数调用占用)。

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