javascript – Promise.then工作执行顺序

The spec says(第5段):

The PendingJob records from a single Job Queue are always initiated in
FIFO order. This specification does not define the order in which
multiple Job Queues are serviced. An ECMAScript implementation may
interweave the FIFO evaluation of the PendingJob records of a Job
Queue with the evaluation of the PendingJob records of one or more
other Job Queues.

这是否意味着我不能指望提供给回调的回调.然后在其他同步控制流中提供给setTimeout的回调之前进行评估?

换句话说,我可以依赖以下打印一两.

setTimeout(() => console.log('two'));
Promise.resolve().then(() => console.log('one'));

解决方法:

Does this mean I can’t count on the callback supplied to .then being evaluated before a callback supplied to setTimeout in an otherwise synchronous control flow?

是的,这就是它的含义;规范不要求实现以这种方式工作.

但实际上,我已经测试过的本机Promise支持的实现已经在完成计划它的“macrotask”之后立即调度了当时的回调(来自PendingJobs队列的“微任务”),在其他待处理的macrotask之前,即使是在微任务之前安排了挂起的macrotask. (setTimeout和事件是macrotasks.)

例如,在我测试它的环境中,它可靠地输出A,C,B:

console.log("A");
setTimeout(_ => console.log("B"), 0);
Promise.resolve().then(_ => console.log("C"));

但JavaScript规范并不要求它.

对于用户代理环境,Bergi points out为其微型任务和宏任务规范中的HTML5 spec covers this.但这仅适用于用户代理环境(如浏览器).

例如,Node不遵循该规范的定义(尤其是因为它的定时器函数返回对象,而不是数字),但Node也给了我们上面的A,C,B,因为(感谢Benjamin Gruenbaum!)它运行了承诺解决方案之后nextTick队列但在任何计时器或I / O回调之前.有关详细信息,请参见his gist.

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...