Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Node.js from exiting while waiting for a callback?

Tags:

node.js

I have code like this:

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);   } }); 

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 in this example is node-mysql.

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

like image 476
mikl Avatar asked Jun 22 '11 15:06

mikl


People also ask

Which is faster promise or callback?

So from my findings i assure you ES6 promises are faster and recommended than old callbacks.

How do you stop asynchronous call in node JS?

When a method is running, and another method is called to stop the first method, I start an infinite loop to stop that code from running and then remove the method from the queue(array).

What is NodeJS timeout?

setTimeout is a built-in Node. js API function which executes a given method only after a desired time period which should be defined in milliseconds only and it returns a timeout object which can be used further in the process.

How do you make a function wait until a callback has been called using node JS?

To make a function wait until a callback has been called using Node. js, we can run our code in the callback that's called when the operation is done. to define the function f that takes the callback parameter. We call that in the callback that's called when myApi.


1 Answers

Callback is Not Queued

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.

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.

like image 167
george calvert Avatar answered Oct 27 '22 23:10

george calvert