gpt4 book ai didi

javascript - 等待 Promise 在 emitter.on 监听器函数中解析

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

someevent 事件被触发时,我只想等待 promise 得到解决,然后再继续。但是slowFunctionThatReturnsPromise需要很长时间才能解决,并且在解决之前整个流程就关闭了。因此它永远不会完成。我本以为使用 then 会等待 promise 得到解决,但我不明白为什么它不等待。

emitter.on('someevent', listener)


var listener = function()
{
x.slowFunctionThatReturnsPromise()
.then(function()
{
console.log('done');
})
}

最佳答案

你不能在 Node.js 描述的“退出”事件上执行此操作

Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. In the following example, for instance, the timeout will never occur:

https://nodejs.org/dist/latest-v7.x/docs/api/process.html#process_event_exit

您可以处理优雅的终止信号,然后在准备好时退出进程。

process.on('SIGINT', () => {
x.slowFunctionThatReturnsPromise().then(function() {
process.exit(0);
})
});

关于javascript - 等待 Promise 在 emitter.on 监听器函数中解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42733691/

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