我在 Node.js 中有下一个对象:
function myObject(){
this.allowed = false;
this.rawData;
}
myObject.prototype.checkAccess = function(){
var self = this;
if (!this.allowed){
fs.readFile("./file.key", function(err, data){
if (err) return;
self.rawData = data;
self.allowed = true;
})
return;
}
// several operations with rawData
// not intended to be called when file.key is read
// but next time checkAccess is called, by example
console.log(this.rawData);
// or, by example, use its content to decrypt
// another file or data from a socket...
var isCorrectlyDecrypted = this.decrypt(this.rawData);
if (!isCorrectlyDecrypted) this.allowed = false;
}
我定期使用 setInterval 调用 checkAccess,但我发现,现有的 file.key 从未更新过 rawData 属性,始终未定义,而允许属性更新成功。
有人可以解释一下发生了什么并告诉我我做错了什么以及最好的方法是什么吗?
编辑:
所以,正如我所说,在使用此类的代码中,我有:
var myObjectInstance = new myObject();
setInterval(function(){
// here some previous code
myObjectInstance.checkAccess();
// and here more code
}, 25)
checkAccess()
的作用是定期查找要读取的 file.key
(如果存在),然后等待下一次调用以处理其内容。因此,console.log() 不适合在读取 file.key 后立即使用,而是在下次调用 checkAccess() 时使用。这就是为什么 console.log()
没有放置在回调中。
最佳答案
这就是异步编程。 console.log(this.rawData)
在 fs.readFile
进程完成之前调用(因为它是回调函数),不会给您任何输出。将 console.log()
放入 fs.readFile
block 中,您将看到所需的输出。
看看 async library 。如果流程完成后需要响应,请使用 async-series 或 async-waterfall。
关于javascript - 我无法在 Node.js 中的 readFile() 回调中更新对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12944022/