gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:15:38 27 4
gpt4 key购买 nike

我无法理解以下代码如何运行。为什么“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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com