promise执行程序函数是您传递给new Promise
的函数。它是同步执行的,因此可以启动promise表示的任何异步过程。
无论答应是否已经兑现,您都始终异步地调用与then
,catch
和finally
附加的回调。
>
因此在您的示例中,在传递给console.log("After resolving the promise");
的{{1}}之前调用console.log
。
下面是一个更清楚地说明这一点的例子:
输出为:
In the executor function
After resolving the promise
In the fulfillment handler: Resolved from the 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
,
Promise的执行程序功能总是被同步调用。
因此,在这一行之后,
let myPromise = new Promise((resolve,reject) =>
resolve("Resolved from the promise");
);
诺言将处于解决状态。
相反,即使在添加回调时承诺已经处于稳定状态,也总是异步调用用then
添加的回调。
本文链接:https://www.f2er.com/2736687.html