简体   繁体   English

我无法在Node.js中的readFile()回调内更新对象属性

[英]I can't update an object property inside the callback of readFile() in Node.js

I have the next object in Node.js: 我在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;
}

I periodically call checkAccess with setInterval but what I found is that, existing file.key, I never have the rawData property updated, being always undefined, while allowed property updates sucessfully. 我定期使用setInterval调用checkAccess,但是发现的是,现有的file.key,我从未更新过rawData属性,始终未定义,同时成功地更新了允许的属性。

Can someone, please, explain what's happening and tell me what I'm doing wrong and what's the best way of doing it? 有人可以请您解释发生的情况并告诉我我做错了什么,什么是最好的做事方法?

EDITED: 编辑:

So, as I said, in the code that uses this class I have: 因此,正如我所说,在使用此类的代码中,我有:

var myObjectInstance = new myObject();

setInterval(function(){

    // here some previous code

    myObjectInstance.checkAccess();

   // and here more code
}, 25)

What checkAccess() does is to look periodically for a file.key to read if present, and then wait until the next call to work with its content. checkAccess()作用是定期查找要读取的file.key (如果存在),然后等待下一次调用以处理其内容。 SO, console.log() is not intended to be used right after file.key is readed, BUT the next times checkAccess() is called and subsecuently. 因此, console.log()不能在读取file.key之后立即使用,但是下次checkAccess()会不成功。 That's why console.log() is not placed inside the callback. 这就是为什么console.log()没有放在回调中的原因。

That's asynchronous programming. 那是异步编程。 console.log(this.rawData) is called before the fs.readFile process is through (as it's a callback-function), giving you no output. fs.readFile进程通过(因为它是一个回调函数)之前,将调用console.log(this.rawData) ,但没有任何输出。 Put the console.log() inside the fs.readFile -block and you'll see the output you want. console.log()放在fs.readFile ,您将看到所需的输出。

Have a look at the async library . 看一下异步库 If you need a response after the process is finished, use an async-series or async-waterfall. 如果在处理完成后需要响应,请使用异步系列或异步瀑布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM