如何防止Node.js在等待回调时退出? [英] How to prevent Node.js from exiting while waiting for a callback?

查看:93
本文介绍了如何防止Node.js在等待回调时退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

var client = new mysql.Client(options);
console.log('Icanhasclient');

client.connect(function (err) {
  console.log('jannn');
  active_db = client;
  console.log(err);
  console.log('hest');

  if (callback) {
    if (err) {
      callback(err, null);
    }

    callback(null, active_db);
  }
});

我的问题是节点在运行时立即终止.它会显示"Icanhasclient",但不会调用回调中的console.log内的任何内容.

My problem is that Node terminates immediately when I run it. It prints 'Icanhasclient', but none of the console.log's inside the callback are called.

(此示例中的mysql为 node-mysql .

(mysql in this example is node-mysql.

是否可以做一些事情以使node.js在退出之前等待回调完成?

Is there something that can be done to make node.js wait for the callback to complete before exiting?

推荐答案

回调未排队

节点运行直到所有事件队列为空.诸如

Node runs until all event queues are empty. A callback is added to an event queue when a call such as

  emmiter1.on('this_event',callback).

已执行.此调用是模块开发人员编写的代码的一部分.

has executed. This call is part of the code written by the module developer .

如果模块是同步/阻塞版本的快速端口,则在操作的某些部分完成之前这可能不会发生,并且所有队列在此之前可能为空,从而允许节点静默退出.

If a module is a quick port from a synchronous/blocking version, this may not happen til some part of the operation has completed and all the queues might empty before that occurs, allowing node to exit silently.

这是一个偷偷摸摸的错误,是模块开发人员在开发期间可能不会遇到的错误,因为它在具有许多 queues 的繁忙系统中很少发生,因为对于所有它们在关键时刻为空.

This is a sneaky bug, that is one that the module developer might not run into during development, as it will occur less often in busy systems with many queues as it will be rare for all of them to be empty at the critical time.

对于用户而言,可能的修复/错误检测程序是在可疑函数调用之前插入特殊的计时器事件.

A possible fix/bug detector for the user is to insert a special timer event before the suspect function call.

这篇关于如何防止Node.js在等待回调时退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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