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

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

问题描述

我有使用es6 async await 语法的非常令人困惑的代码段.我希望发生的事情是,该过程永远挂在 await 行上,因为从未调用过resolve函数.但是,实际上发生的是输出开始",然后退出该过程,没有更多输出.

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会添加到此引用计数中.当时间/请求解析时,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

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

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