在 readFile 中访问外部范围变量

Access outer scope variable in readFile

我是异步编程的新手。最近我发现了一个我不太明白的案例。对于此示例:

var username = "abc";
fs.readFile(filePath, { encoding: 'utf-8' }, function (err, oldUsername) {
    console.log(username); // Print xyz
    if (username == oldUsername) 
        // do something, since username is now 'xyz', result failed!
});
username = "xyz";

我想将文件中的 oldUsernameusername (abc) 进行比较,但控制台打印 "xyz"所以结果失败了。

如何获取用户名的未修改值?

你必须记住,那个回调函数中的所有代码,它实际上并不是 运行,直到该代码中的所有其他内容 运行s.

你只是在那里定义函数,而不是执行它。您将它作为参数传递给另一个函数 (readFile),因此它会在异步完成时调用它 i/o.

我想这有点像在信封上放一个 return 地址,在处理完信封上的主地址之前,这并不重要。

因此,在 console.log 执行之前,您最终会在最后分配一个不同的值。

有更多信息,例如:

A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an IndexedDB query to return or an XHR request to return, it can still process other things like user input. [1]

祝你好运! :)