Sunday, June 23, 2019

javascript - 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");




Answer




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.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...