JohnSnow
JohnSnow

Reputation: 7111

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.

Upvotes: 3

Views: 6313

Answers (3)

Ula
Ula

Reputation: 2748

I hope that the following will help someone else having similar problem with reading values from MongoDB using socket io.

In those cases you can use the following code (both functions on server side):

socket.on('readTopicMessages', (intGr, callback) => {

  readTopicChats(intGr, function (data){
    io.emit('topicMessages', data);
  });
});  

function readTopicChats (intGr, callback){
  All_Chats
  .find({ 'intGr': intGr.intGr })
  .sort([['dateTime', 'ascending']])
  .exec(function (err, data){
    return callback(data);
  });
}

Upvotes: 0

Supradeep
Supradeep

Reputation: 3266

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

Upvotes: 3

Antonio Val
Antonio Val

Reputation: 3340

Because the map() method by definition returns an array, and fs.readdir() returns undefined.

Why it returns undefined is because it is an asynchronous function, the result is not returned by the function but in the callback you have to wait, that's because you have to do the console.log inside that callback function.

Just for your information, the fs module has synchronous version of the methods as well, so in this case you could do:

console.log(fs.readdir("ab"))

But using the synchronous version you are blocking your code until you get the result, so it would not be recommended depending on the situation; that's up to your case.

Upvotes: 0

Related Questions