我的代码是这样的:
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);
}
});
我的问题是当我运行Node时,它会立即终止。它打印'Icanhasclient',但是回调中的console.log都不会被调用。
(本例中mysql为node-mysql。
有没有什么办法可以让node.js在退出前等待回调完成?
发布于 2014-04-29 09:40:21
您可以只使用setInterval发出setTimeout或循环超时。
如果要检查退出条件,还可以执行条件超时:
(function wait () {
if (!SOME_EXIT_CONDITION) setTimeout(wait, 1000);
})();
将此代码放在代码的末尾,控制台将会等待……等等..。直到你想让它关闭。
发布于 2017-07-21 05:53:59
我的解决方案是实例化一个EventEmitter,并侦听我的自定义事件。
var eventEmitter = new process.EventEmitter();
然后我从异步回调中调用了eventEmitter.emit
:
client.connect(function (err) {
eventEmitter.emit('myevent', {something: "Bla"})
});
我的脚本中的最后一件事是eventEmitter.on
eventEmitter.on('myevent', function(myResult){
// I needed the result to be written to stdout so that the calling process could get it
process.stdout.write(JSON.stringify(myResult));
});
节点将一直等待,直到事件处理程序完成运行。
发布于 2018-05-21 23:04:15
基于@Todd的回答,我创建了一个一行程序。将其包含在脚本的开头,并在完成后设置done = true
:
var done = (function wait () { if (!done) setTimeout(wait, 1000) })();
示例:
var done = (function wait () { if (!done) setTimeout(wait, 1000) })();
someAsyncOperation().then(() => {
console.log('Good to go!');
done = true;
});
它怎麽工作?如果我们稍微扩展一下:
// Initialize the variable `done` to `undefined`
// Create the function wait, which is available inside itself
// Note: `var` is hoisted but `let` is not so we need to use `var`
var done = (function wait () {
// As long as it's nor marked as done, create a new event+queue
if (!done) setTimeout(wait, 1000);
// No return value; done will resolve to false (undefined)
})();
https://stackoverflow.com/questions/6442676
复制相似问题