'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:
- define
fs - define
tempset to??? - define
testfunction - define
prfunction - call
test()function - within
test()call thefs.readdir()but then return immediately fromtest()without the callback having been executed yet setTimeout(pr,1000,"Out setTimeout print: "+temp);(where the value oftempat that moment - still "???" - becomes part of the string that setTimeout will pass toprin one second's time)- the callback from
fs.readdir()is executed, and only then doestempget 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 |
