简体   繁体   中英

How to refer and assign to a global variable inside an anonymous function?

I am reading from a json file and assign the json to a global variable, but it seems to not work as the global variable remains undefined.

var libObj;

fs.readFile('library.json', 'utf8', function(err, data) {
    if (err){
        console.log(err);
    } else {
        libObj = JSON.parse(data);
    }
});

This is because the callback is non-blocking and asynchronous and gets called some indeterminate time in the future and does not execute sequentially from top to bottom.

If you add extra logging, you can see what happens:

var libObj;

console.log("before");
fs.readFile('library.json', 'utf8', function(err, data) {
    console.log("callback called");
    if (err){
        console.log(err);
    } else {
        libObj = JSON.parse(data);
        console.log(libObj);
    }
});
console.log("after");

This will product this output:

before
after
callback called
your data here

So, you can see the assignment works just fine, it just happens after you were trying to use the variable.


The usual way you solve this is you use the result of the fs.readFile() inside the callback or you call some function from within that callback.

fs.readFile('library.json', 'utf8', function(err, data) {
    if (err){
        console.log(err);
    } else {
        console.log(data);
        // use data here
        // or call a function and pass it the data here
        someFunc(data);
    }
});
// don't try to use data here, it's not available yet

This is your typical problem with asynchronous code execution. You example code does NOT execute from top to bottom. In particular, your anonymous function does NOT get executed. you need to understand the global context concept. to fix that you need to execute all the code belongs to readFile function inside it's all callback like this:

fs.readFile('library.json', 'utf8', function(err, data) {
 if (err){
    console.log(err);
 } else {
    libObj = JSON.parse(data);
    executeMoreCode() //for exemple
 }
});

function executeMoreCode() {
  console.log('hello');
}

then create a function outside of the readFile function context box and call it wheneva you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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