简体   繁体   English

修改和传递全局变量

[英]Modifying and passing global variables

I'm having trouble modifying a global variable in a callback. 我在修改回调中的全局变量时遇到问题。

I need to reload the data from a file every hour. 我需要每小时从文件中重新加载数据。 It works fine if I use readFileSync but not if I use the normal readFile : 如果我使用readFileSync可以正常工作,但是如果我使用普通的readFile

var MY_GLOBAL = {};

fs.readFile("some_path", function (err, data) {
    if (err) throw err;
    MY_GLOBAL.some_name = data;
    });

setInterval(function() {
    fs.readFile("some_path", function (err, data) {
        if (err) throw err;
        MY_GLOBAL.some_name = data;
        }
    }, 60 * 60 * 60 * 1000);

I have another module named router.js which contains all the routing for my application. 我还有一个名为router.js模块,其中包含应用程序的所有路由。

I call it using: router(app, MY_GLOBAL) . 我称它为: router(app, MY_GLOBAL)

My issue is that although MY_GLOBAL gets set in the readFile callback, it doesn't update in the router. 我的问题是,尽管在readFile回调中设置了MY_GLOBAL ,但它并未在路由器中更新。 I need to access the updated data every hour. 我需要每小时访问一次更新的数据。

I can suggest several things to check. 我可以建议检查几件事。

First, I would double check that the callback function is executing for certain using console.log or alert . 首先,我将使用console.logalert再次检查回调函数是否正在执行。

I would also like to point out that objects are passed by reference in Javascript, which means that the object passed in to router is a reference to MY_GLOBAL , not a copy of MY_GLOBAL . 我还想指出的是,对象是通过引用在Javascript中通过,这意味着传入的对象router是一个参考MY_GLOBAL ,不是副本MY_GLOBAL Where this can go wrong is if somewhere you reassigned MY_GLOBAL. 如果您在某处重新分配了MY_GLOBAL,这可能会出错。 I would make sure that you did not reassign MY_GLOBAL anywhere. 我会确保您没有在任何地方重新分配MY_GLOBAL。

Also, if data is an object (as opposed to a string, number, or boolean), you need to check that it doesn't get reassigned, either. 另外,如果data是一个对象(与字符串,数字或布尔值相对),则需要检查它是否也没有被重新分配。 For example, if you read the value of MY_GLOBAL.some_name inside of router , it is possible that you could retain a reference to an old version after data is assigned to MY_GLOBAL.some_name. 例如,如果您在router内部读取MY_GLOBAL.some_name的值,则可能在将data分配给MY_GLOBAL.some_name之后可以保留对旧版本的引用。

If its a global statement why not try to use the module keyword such a lot of people does with the window . 如果它是一个全局语句,为什么不尝试使用module关键字,那么很多人会使用window

another thing. 另一件事。 You want the function code to be executed every hour. 您希望功能代码每小时执行一次。 you are putting one extra 60 multiplication into the second parameter. 您要在第二个参数中再增加一个60乘法。 try this. 尝试这个。

module.MY_GLOBAL = {};

var callbackFunction = function(){
  fs.readFile("some_path", function (err, data) {
    if (err) throw err;
    module.MY_GLOBAL.some_name = data;
  }
};
callbackFunction();
setInterval(callbackFunction , 60 * 60 * 1000); // 360000 == 1 hour

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

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