Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value of a callback function in Node.js

I have a question about callback functions. Consider this simple code:

var array = [1,2,3];

   console.log(array.map(function(val){

   return val * 2

}))

This will correctly log back to the console [2,4,6] which means it is "returning" that value back.

Now consider this (NOTE: assume "ab" to be a valid directory)

fs.readdir("ab",function(err,data){
   console.log(data)
})

This code works fine and will print an array of filenames in the directory "ab" to the terminal. However, the same code:

console.log(fs.readdir("ab",function(err,data){
    return data
}))

This will print undefined.. why is this? if in the previous snippet I can log data to the terminal, why can't I return the value and log it to the console? And how is the first snippet including the map method working using this same logic?

Thank you.

like image 376
JohnSnow Avatar asked Aug 12 '26 22:08

JohnSnow


1 Answers

fs is an Asynchronous function, it doesn't return the values as it doesn't know when the value will be available due to which it logs undefined.

When you say console.log(fs.readdir()), it reads the fs function and checks if it is returning anything which in this case is undefined and hence logs it. The execution didn't go inside the callback of fs.readdir() yet as it is asynchronous as takes time for that to complete.

fs.readdir() is like a promise, it calls to read the directory and forget about it till the reading operation is done and after which it's callback function is called. Hence, we pass callback functions which will be called back when the asynchronous operation is done executing like below :

function readFile (callback){
 fs.readdir("ab",function(err,data){
   return callback(data);
 });
}

readFile(function (data){
  console.log(data);
});
like image 88
Supradeep Avatar answered Aug 14 '26 10:08

Supradeep



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!