Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js and asynchronous programming palindrome

This question might be possible duplication. I am a noob to node.js and asynchronous programming palindrome. I have google searched and seen a lot of examples on this, but I still have bit confusion.

OK, from google search what I understand is that all the callbacks are handled asynchronous. for example, let's take readfile function from node.js api

fs.readFile(filename, [options], callback) // callback here will be handled asynchronously fs.readFileSync(filename, [options])

  var fs = require('fs');

    fs.readFile('async-try.js' ,'utf8' ,function(err,data){
        console.log(data);   })

    console.log("hii");

The above code will first print hii then it will print the content of the file.

So, my questions are:

  1. Are all callbacks handled asynchronously?
  2. The below code is not asynchronous, why and how do I make it?

    function compute(callback){
     for(var i =0; i < 1000 ; i++){}
     callback(i);
    
    }
    
    function print(num){
     console.log("value of i is:" + num);
    }
    
    
    compute(print);
    console.log("hii");
    
like image 334
Rushabh RajeshKumar Padalia Avatar asked Dec 04 '25 07:12

Rushabh RajeshKumar Padalia


2 Answers

Are all callbacks handled asynchronously?

Not necessarily. Generally, they are, because in NodeJS their very goal is to resume execution of a function (a continuation) after a long running task finishes (typically, IO operations). However, you wrote yourself a synchronous callback, so as you can see they're not always asynchronous.

The below code is not asynchronous, why and how do I make it?

If you want your callback to be called asynchronously, you have to tell Node to execute it "when it has time to do so". In other words, you defer execution of your callback for later, when Node will have finished the ongoing execution.

function compute(callback){
 for (var i = 0; i < 1000; i++);

 // Defer execution for later
 process.nextTick(function () { callback(i); });
}

Output:

hii
value of i is:1000

For more information on how asynchronous callbacks work, please read this blog post that explains how process.nextTick works.

like image 118
user703016 Avatar answered Dec 07 '25 01:12

user703016


No, that is a regular function call.

A callback will not be asynchronous unless it is forced to be. A good way to do this is by calling it within a setTimeout of 0 milliseconds, e.g.

setTimeout(function() { 
   // Am now asynchronous
}, 0);

Generally callbacks are made asynchronous when the calling function involves making a new request on the server (e.g. Opening a new file) and it doesn't make sense to halt execution whilst waiting for it to complete.

like image 37
George Reith Avatar answered Dec 07 '25 03:12

George Reith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!