Node.js中的异步IO无法在对象中更新参考



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

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

函数oniroperizereport((能够获取JSON,但是任何尝试MyReport.Report的尝试都只能获得null,就好像从未分配过。

为什么会发生?

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

快速解决方案可以是:

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

替代解决方案可以是:

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

最新更新