JavaScript Promise Callback是否异步执行 [英] Is JavaScript Promise Callback executed Asynchronosuly
问题描述
假设我有这段代码
function y(resolve, reject)
{
console.log("Result");
resolve();
}
var promise = new Promise(y);
我想知道的是函数 y
将异步执行或不执行。
What I want to know is whether the function y
will be executed asynchronously or not.
推荐答案
这取决于承诺的实现。如果我们查看规范。您可以在此处找到最终规范 - 因为这个答案最初是写的,所以已经敲定。
It depends on the implementation of the promise. If we check the spec. You can find the final spec here - since this answer was originally written, it has been finalized.
这是相关的摘录(你可以找到原始来源这里)
Here is the relevant excerpt (you can find the original source here)
- 让完成为Call(执行者,未定义,«resolvingFunctions。[[Resolve]],resolvingFunctions。[[Reject]]»)。
- 如果完成是突然完成,那么
- 让状态为Call(resolvingFunctions。[[Reject]],undefined,«completion。[[value]]»)。
- ReturnIfAbrupt(状态)。
ES6标准表示承诺的履行始终异步(参见第25.4.5.3节, Promise.prototype.then
以及随附的第25.4.5.3.1节, PerformProm iseThen
)。我已在下面放置相关资料。
The ES6 standard indicates that the fulfillment of a promise is always asynchronous (See section 25.4.5.3, Promise.prototype.then
and accompanying section 25.4.5.3.1, PerformPromiseThen
). I have placed the relevant material below.
- 否则,如果promise的[[PromiseState]]内部槽的值为已满足,则
- 让value为promise的[[PromiseResult]]内部值插槽。
- 执行EnqueueJob(PromiseJobs,PromiseReactionJob,«fulfillReaction,value»)。
- 让reason成为promise [[PromiseResult]]的值内部插槽。
- 执行EnqueueJob(PromiseJobs,PromiseReactionJob,«rejectReaction,reason»)。
TLDR :传递给promise的函数是同步执行的,但后续然后
调用始终是异步执行的。
TLDR: the function passed to the promise is executed synchronously, but subsequent then
calls are always executed asynchronously.
这篇关于JavaScript Promise Callback是否异步执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!