Ad

Javascript Scope Unexpected Results

- 1 answer

I've been battling with this problem for a few hours now, my js code which I am running in node.js is below.

setInterval(function () {
    var exampleVar;
    exec('cat /path/to/unimportant/file', function (error, stdout, stderr) { // This function returns errors, stdout and stderr
        console.log(stdout); // correct value
        exampleVar = stdout;
        console.log(exampleVar); // correct value
    }
    console.log(exampleVar); // undefined
}, unimportantTime);

I would think that because the variable has already been declared by the function exec created's parent scope, that I would be able to assign a value to it. Can someone explain what I'm doing wrong and the correct method for accessing an out of scope variable?

Ad

Answer

Your problem is not one of scope, but of synchronicity.

In Node.js, most functions are asynchronous by default, which means that the execution of your program continues regardless of whether these functions have actually finished running.

So what happens is that your last console.log(exampleVar) executes before the function passed to exec has had time to be executed (as IO operations are typically way slower than executing cached JS code).

See this primer for a more in-depth explanation.

Ad
source: stackoverflow.com
Ad