简体   繁体   中英

Callback function in node.js

I am new to node.js and relatively new to javascript. I have understood how callbacks works and wanted to try out a function myself. Here is my code:

MyScript.js:

 var calledfunction = function()

 { 

     console.log("This is a called function");

     for(i=0;i<1090660;i++)

     {  


        console.log(i);

     } 


     console.log('done');

 };

var sayHello = require('./sayhello.js');

objhello = new sayHello();

objhello.setupSuite(1,calledfunction); 

console.log('Next statement;');

sayhello.js

var _ = require('underscore');
module.exports = exports = CLITEST;

function CLITEST(param1,param2)
{
}


_.extend(CLITEST.prototype, {
  setupSuite: function (here,callback) {
  console.log(here);
  console.log('This is a callback function');
   callback();
  }
  })

The above program is run by executing > node Myscript.js

My question is : the for loop consumes 50 secs to execute and print all the numbers in the console and then only executes the line "Next statement" which is outside the callback function .

Why is this happening? because I read theories saying that the immediate statements will be executed without having to wait for the function to get executed.

The ideal output should have been : print " Next statement" and then print the contents of the for loop

but in the above case it is vice versa ?

This is not a real callback, but rather a simple function call . Function calls are obviously synchronous, as the following statements may rely on their return values.

In order to may the callback async you can use: setTimeout or setImmediate , depending on the actual use case.

See also: Are all Node.js callback functions asynchronous?

As pointed out by one of the commenters, your code is executed in a synchronous fashion. The function calls are executed one after the other, thus no magic is happening and the console.log('Next statement;'); call is executed after the execution of the callback. If you were in a situation in which you had to call a function which executed an asynchronous call (ie, an AJAX call with a callback) then yes, you would expect the subsequent console.log to be executed right after the asynchronous call.

In other words, in your case the code represents a simple function call, while an asynchronous call would offload the computation of the callback somewhere else, thus the execution of the code where the callback function was called keeps going by printing the statement and won't wait for the execution of the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM