如何在嵌套回调中从父作用域访问(和修改)参数和变量?

时间:2014-07-01 23:21:20

标签: javascript node.js

有人可以解释为什么有些变量没有传递给readFile的回调,而其他变量是?

// response is http response writer obj
var process = function (response, file) {

    var calculator = new mycalc.Calculator();

    var output1 = "no-error";
    var that = this;

    try {
        fs.readFile(file, 'utf8', function (err, data) {
            if (err) {
                that.output1 = "check1";
            }

            output1 = "check2";
            response.write(output1);

            // not even working with that.output1

            // more stuff will come here
        });
    } catch (e) {
        response.write(e.stack);
    }

    response.write(output1);
};


的问题:

  • response.write()不会在回调函数中写入,但它会从process()函数范围成功写入。

  • output1打印“无错误”,而预期结果为“check1”或“check2”

0 个答案:

没有答案