javascript - 当 Promise 的解析取决于 setTimeout 时,JS 事件循环如何表现?

标签 javascript node.js multithreading promise

console.log('1')
setTimeout(() => {
    console.log('2')
}, 0)
function three() {
    return new Promise(resolve => {
        setTimeout(() => {
            return new Promise(resolve => resolve('3'))
        },0)
    })  
}
three().then(result => console.log(result))
console.log('4')

此代码片段输出1 4 2

根据我对 javascript 事件循环和并发模型的理解,这是我所期望的行为。但这给我留下了一些挥之不去的问题。

在回答这些问题之前,我将首先分解我对此代码片段的理解。

为什么代码输出1

无需解释

为什么代码输出4

输出 2 的回调在 0ms 后加载到事件队列(又名宏任务队列)中,但直到主调用堆栈清空后才会执行。

即使 two 是立即解决的 Promise,其代码也会加载到作业队列(又名微任务队列)中,并且在主调用堆栈清空之前不会执行(无论事件队列的内容)

为什么代码输出2

console.log(4)之后,主调用堆栈为空,JavaScript 会查找下一个回调以加载到主堆栈上。可以相当安全地假设,此时某些“工作线程”已经将输出 2 的回调函数放入宏任务队列中。它被加载到堆栈上并输出 2。

为什么代码不输出 3

这对我来说有点模糊。函数two返回一个在主线程中then编辑的promise。通过 then 传递的回调函数被加载到微任务队列中,并在宏任务队列中的下一个任务之前执行。因此,虽然您可能认为它会在记录 2 的回调之前运行,但实际上理论上它根本不可能运行。这是因为 Promise 仅通过其 setTimeout 的回调函数来解析,并且该回调函数(由于 setTimeout)仅在主执行线程(等待 Promise 解析的同一线程)为空时才会运行。

为什么这让我烦恼

我正在尝试建立一个关于 javascript 如何处理并发性的完整理论思维模型。该模型中缺失的部分之一是网络请求、 promise 和事件循环之间的关系。拿上面的代码片段来说,假设我用某种网络请求(异步 Web 开发中非常常见的事情)替换 Three 的 setTimeout 。假设网络请求的行为与 setTimeout 类似,因为当“工作线程”完成时,回调被推送到宏任务队列,我很难理解该回调是如何执行的。但这确实是一直在发生的事情。

谁能帮我理解一下吗?我目前对js并发的理解是否还有遗漏的地方?我做出了错误的假设吗?这实际上有任何意义吗?哈哈

最佳答案

Why code does NOT output 3

在此代码中:

function three() {
    return new Promise(resolve => {
        setTimeout(() => {
            return new Promise(resolve => resolve('3'))
        },0)
    })  
}
three().then(result => console.log(result))

你永远不会解析 third() 创建的第一个 Promise。由于这是从 two() 返回的,因此 two().then(...) 中的 .then() 处理程序> 从未被调用。

您确实解析了计时器内创建的 promise ,但您仅将该 promise 返回给计时器回调,而计时器回调不执行任何操作。

如果您将代码更改为:

function three() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('3');
        },0)
    })  
}
three().then(result => console.log(result))

然后,您将看到 3get 输出。

所以,这与事件循环或其工作方式没有任何关系。它与未解析 two() 返回的 Promise 有关,因此该 Promise 上的 .then() 处理程序永远不会被调用。

<小时/>

I'm trying to build a complete theoretical mental model of how javascript handles concurrency. One of the missing pieces in that model is the relationship between network requests, promises, and the event loop. Take the above code snippet, and suppose I replace three's setTimeout with some sort of network request (a very common thing in async web development). Assuming that the network request behaves similarly to setTimeout, in that when the "worker thread" is done, a callback is pushed to the macro task queue, it's hard for me to understand how that callback even gets executed. But this is something that happens literally all the time.

网络请求、 promise 和计时器都经过事件循环。关于如何同时排列队列中的多个事件相对于彼此的优先级,有非常复杂的规则。 .then() 处理程序通常优先考虑。

将 Javascript 解释器视为这个简单的序列。

 Get event from event queue
 If nothing in the event queue, sleep until something is in the event queue
 Run callback function associated with the event you pull from the event queue
 Run that callback function until it returns
     Note, it may not be completely done with its work because it may
     have started other asynchronous operations and set up its own
     callbacks or promises for those.  But, it has returned from the
     original callback that started it
 When that callback returns, go back to the first step above and get the next event

请记住,网络请求、 promise 、计时器以及 Node.js 中的所有异步操作都以这种方式通过事件队列。

关于javascript - 当 Promise 的解析取决于 setTimeout 时,JS 事件循环如何表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58619618/

相关文章:

javascript - 在 mouseenter 上使用动态 div id 显示/隐藏表格列

Javascript : Unexpected empty element in array with different key types?

javascript - Kubernetes 替换部署失败

python - 如何在 ubuntu 12.04 上为 node.js 安装 nvm

java - 捕获 Java 中特定线程的控制台输出

c - C中成功创建线程返回的错误状态

javascript - Youtube iframe API : OnReady not firing for Chrome extension

javascript - 使用 babel,如何将一些代码附加到每个文件的顶部?

node.js - npm 不会安装包 "npm ERR! network tunneling socket could not be established, cause=Parse Error"

c++ - 使用pthread在c++中运行后台进程