Node.js 中的异步 IO 无法更新对象中的引用

Asynchronous IO in Node.js fails to update reference in object

我已将我的问题简化为以下内容:

var fs = require("fs");
var async = require("async");


var myReport;

function Report() {

    this.report = null;

}

Report.prototype.initializeReport = function(callback) {    

    fs.readFile("./scrape reports/Scrape Report 1522604653782", "utf-8", function(err, data) {

        this.report = JSON.parse(data);
        console.log("Found this report: " + this.report);

        callback();
    });

}

module.exports = function() {

    myReport = new Report();

    myReport.initializeReport(function() {
        console.log(myReport.report);
    });
};

当我运行这个时,输出如下:

> Found this report: [object Object]
> null

函数 initializeReport() 能够获取 JSON,但之后任何引用 myReport.report 的尝试只会得到 null,就好像它从未被分配过一样。

为什么会这样?

在您的 fs.readFile 函数中,响应 this.report 实际上并未指向 myReport 对象。因此,在使用 null 启动后,您从未分配给 myReport.report 属性。

快速解决方案可以是:

只需分配给 myReport.report 而不是 this.report

替代解决方案可以是:

您可以使用 javascript 的 bindapply 函数绑定函数的上下文。