为什么 Nodejs 回调()无法访问回调范围之外的变量?
总的来说,我对 NodeJS 和 JavaScript 还很陌生。这是我的脚本:
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???
如何在回调之外更改 var temp 的值?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
相同
与此时
temp
仍然是"???"
。你必须使用is the same as
At this point of time
temp
still is"???"
. You have to use日志语句在控制台中显示的顺序是什么?
我不喜欢 node.js,但我希望在“inter”之前看到“Out”,因为我猜测
fs.readdir()
函数是异步的,并且回调您提供给它的函数只有在您在代码的最后一行中调用setTimeout()
之后才会执行,此时temp
还没有执行却被改变了。也就是说,我期望您的代码的执行顺序是:
fs
temp
set to???
test
函数pr
函数test()
函数test()
中调用fs.readdir() 但立即从
test()
返回,而回调尚未执行setTimeout(pr,1000,"Out setTimeout print: "+temp);
(此时temp
的值 - 仍然是“???” - 成为setTimeout 将在一秒内传递给pr
的字符串)fs.readdir()
的回调,然后才执行temp
换衣服吧。 “inter”超时已设置。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 tosetTimeout()
in the last line of your code at which pointtemp
has not yet been changed.That is, the sequence of execution I would expect from your code is:
fs
temp
set to???
test
functionpr
functiontest()
functiontest()
call thefs.readdir()
but then return immediately fromtest()
without the callback having been executed yetsetTimeout(pr,1000,"Out setTimeout print: "+temp);
(where the value oftemp
at that moment - still "???" - becomes part of the string that setTimeout will pass topr
in one second's time)fs.readdir()
is executed, and only then doestemp
get changed. The "inter" timeout gets set.