当 Promise 永远不会解决时会发生什么? [英] what happens when a Promise never resolves?

查看:34
本文介绍了当 Promise 永远不会解决时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段使用 es6 async await 语法的非常混乱的代码片段.我期望发生的是该进程永远挂在 await 行上,因为从不调用 resolve 函数.然而,实际发生的是输出start",然后进程退出,没有更多输出.

I have this very confusing snippet of code using es6 async await syntax. What I would expect to happen is that the process hangs on the await line forever, since the resolve function is never called. However, what actually happens is that "start" is outputted and then the process exits with no more output.

const simple = async () => {
  console.log('start')
  await new Promise(resolve => {})
  console.log('done.')
}
simple()

但是,下面的代码将打印开始",等待 1 秒,然后打印完成".

this code below however, will print "start", wait 1 second, and the print "done."

const simple = async () => {
  console.log('start')
  await new Promise(resolve => setTimeout(resolve, 1000))
  console.log('done.')
}
simple()

我对这意味着什么最接近的猜测(没有任何证据)是,当节点在等待承诺时,它会跟踪代码中发生的活动,当没有其他事情发生时,它只是退出.有人可以解释为什么代码在这里退出吗?

My closest guess to what this means (without any evidence) is that while node is waiting on a promise, it keeps track of the active things happening in your code, when there is nothing else happening, it simply exits. Can someone explain why the code exits here?

运行 node v8.7.0

推荐答案

我最接近的猜测……它会跟踪代码中发生的活动,当没有其他事情发生时,它会直接退出.

My closest guess … it keeps track of the active things happening in your code, when there is nothing else happening, it simply exits.

这基本上是正确的.节点保持对计时器和网络请求等事物的引用计数.当您发出网络或其他异步请求时,设置计时器等.节点会添加到此引用计数中.当次数/请求解析 Node 从计数中减去时.

This is essentially correct. Node keeps a reference count of things like timers and network requests. When you make a network, or other async request, set a timer, etc. Node adds on to this ref count. When the times/request resolve Node subtracts from the count.

这个计数是 Node 在事件循环结束时决定是否退出的方式.当您到达事件循环的末尾时,Node 会查看此计数,如果为零则退出.简单地做出承诺,不会增加引用计数,因为它不是异步请求.

This count is how Node decides whether to exit at the end of the event loop. When you get to the end of the event loop Node looks at this count and if it's zero exits. Simply making a promise, doesn't add to the ref count because it's not an async request.

[Node 核心开发人员] Bert Belder 对此进行了很好的讨论,很有帮助:https://www.youtube.com/watch?v=PNa9OMajw9w

There's a good talk about some of this by [Node core developer] Bert Belder that's helpful: https://www.youtube.com/watch?v=PNa9OMajw9w

这篇关于当 Promise 永远不会解决时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆