smorhaim
smorhaim

Reputation: 798

What is the scope of JS variables in anonymous functions

Why does this code returns $products empty? If I test for $products inside the function it does show data... but once it finishes I can't seem to get the data.

var $products = new Array();
connection.query($sql, function(err, rows, fields) {
    if (err) throw err;
    for(i=0; i< rows.length; i++)
    {
        $products[rows[i].source_identifier] = "xyz";
    }

});
connection.end();

console.log($products); // Shows empty.

Upvotes: 1

Views: 61

Answers (1)

Pointy
Pointy

Reputation: 413720

It doesn't return it empty; there's no return statement. The issue is that the operation is asynchronous. When your console.log() call runs, the query has not yet completed.

Move your console.log() call to inside that callback function, after the for loop. (Also declare "i" with var !!!)

The whole point of using APIs that involve callbacks like that is to cope with the fact that the operations are asynchronous. If they were synchronous, it'd be weird to design such an interface.

Upvotes: 2

Related Questions