Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a node.js script alive while promises are being resolved?

My script performs some asynchronous tasks using promises (with the q library). Running mocha tests works fine. However running the script from the command line does not. The node process immediately dies.

var bot = require('./bot');

bot.getCategories().then(function (categories) {
  console.log('Found ' + categories.length + ' categories');
});
like image 752
Kees de Kooter Avatar asked Sep 15 '15 11:09

Kees de Kooter


2 Answers

My script performs some asynchronous tasks using promises (with the q library). Running mocha tests works fine. However running the script from the command line does not. The node process immediately dies.

This is most certainly a bug, please do report it. The Node.js environment should not exit prematurely while there are things still queued in the event loop.

You should not have to alter your code one bit for this to happen. The Q library (keep in mind there are more modern and native alternatives today) schedules async callbacks on the process.nextTick "microtask" queue. Your bot library presumably also performs IO, both these things should cause node not to terminate.

like image 181
Benjamin Gruenbaum Avatar answered Oct 23 '22 12:10

Benjamin Gruenbaum


Node.js will exit when there are no more callbacks to process. You can use setInterval or setTimeout to always keep one so that the process does not automatically exit.

function wait () {
   if (!EXITCONDITION)
        setTimeout(wait, 1000);
};
wait();
like image 38
Hyo Byun Avatar answered Oct 23 '22 11:10

Hyo Byun