'Why Nodejs callback() can't access variable outside callback scope?

I am fairly new to NodeJS and to JavaScript in general. Here is my script:

var fs = require('fs') ;

var temp = "???";

var test = function (){
    fs.readdir("./", function(err,result){
    temp = result;            // i change the temp's value
    console.log("inter result ....."+temp);        //  temp's value changed
    setTimeout(pr,1000,"inter setTimeout: "+temp);  //  temp's value changed 
    });
}

var pr = function (str){
    console.log("Print str: "+ str);
} ;


test();

setTimeout(pr,1000,"Out setTimeout print: "+temp);  //  Why here temp's value not change???

How can I change to the var temp’s value outside the callback?



Solution 1:[1]

What order do the log statements appear in your console?

I'm not into node.js, but I would expect to see the "Out" one before the "inter" ones because I would guess the fs.readdir() function is asynchronous and that the callback function that you provide to it will not be executed until after you've already made the call to setTimeout() in the last line of your code at which point temp has not yet been changed.

That is, the sequence of execution I would expect from your code is:

  1. define fs
  2. define temp set to ???
  3. define test function
  4. define pr function
  5. call test() function
  6. within test() call the fs.readdir() but then return immediately from test() without the callback having been executed yet
  7. setTimeout(pr,1000,"Out setTimeout print: "+temp); (where the value of temp at that moment - still "???" - becomes part of the string that setTimeout will pass to pr in one second's time)
  8. the callback from fs.readdir() is executed, and only then does temp get changed. The "inter" timeout gets set.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nnnnnn