3

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.

3 Answers 3

3

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);
});
Sign up to request clarification or add additional context in comments.

5 Comments

So in the event that you are console.logging (like in my example) console.log() would be the callback of the fs.readdir function ?
No. console.log() in your example is executed in the callback of fs.readdir() after it got executed.
how we can use data value to front end rendering?
@AjitSingh This is in the server. To use this in the front end client, you need to send this data to the front end through an API. Write an api that will do the above file system operation and returns the data
@superUser if i have function in side my router the can i render to front end like this res.render('aspects',{ results : results, });
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.