javascript - "event loop queue"和 "job queue"和有什么区别?

标签 javascript promise es6-promise event-loop job-queue

我无法理解以下代码如何运行。为什么“1”在“b”之后,而“h”在“3”之后?顺序不应该是:a、b、1、2、h、3吗?有些文章说“事件循环队列”和“作业队列”之间的差异导致了以下输出。但如何呢?我已阅读ECMAScript 2015 - 8.4 Jobs and Job Queues的规范,想知道Promise'job是如何运作的,但这让我更加困惑。有人能帮我吗?谢谢!

var promise = new Promise(function(resolve, reject) {resolve(1)});
promise.then(function(resolve) {console.log(1)});
console.log('a');
promise.then(function(resolve) {console.log(2);});
setTimeout(function() {console.log('h')}, 0);
promise.then(function(resolve) {console.log(3)});
console.log('b');

// a
// b
// 1
// 2
// 3
// h

我知道Promise是异步的,但是setTimeout(..)异步操作的回调总是在Promise的异步操作之后。为什么?

最佳答案

Why "1" is after "b"?

promise 规范规定所有 promise .then()处理程序必须在调用堆栈清空后异步调用。因此,在调用堆栈上同步执行的 ab 都将在任何 .then() 处理程序之前执行,因此 1 始终位于 ab 之后。

一些有趣的阅读:

  1. Tasks, microtasks, queues and schedules .
  2. What is the order of execution in JavaScript promises?
  3. Writing a JavaScript framework - Execution timing, beyond setTimeout .
<小时/>

线程“Promises wiggle their way between nextTick and setImmediate”中有一些很好的建议:

I would not recommend relying on the exact execution order of non-chained events. If you want to control the execution order - rearrange the callbacks in a way so that the one that you want to be executed later depends on the one that you want to be executed earlier, or implement a queue (that does the same behind the hood).

换句话说,如果您依赖于异步事件的特定顺序,那么您实际上应该链接它们,而不是依赖于实现中未指定的调度。

关于javascript - "event loop queue"和 "job queue"和有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40880416/

相关文章:

javascript - 需要 angularjs SPA 的建议

Firefox 中的 JavaScript 弹出窗口

javascript - 如何打印带缩进的 HTML 代码?

javascript - 在外部范围事件上触发 Promise.fulfill

node.js - 返回一个 Promise,无需等待 Node.js 函数中的依赖 Promise

javascript - 单击特定超链接时切换对象的可见性

javascript - 为什么 Backbone Collection fetch 不返回 promise

javascript - 从 json 构建 Promise 流程

javascript - 何时不使用 promise

javascript - 未捕获的 TypeError : XXX. 那么不是一个函数