1

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.
1
  • 4
    Welcome to the wonderful world of async! You can't do that. Commented Nov 1, 2012 at 22:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

My first instinct was that this was an asynch issue.... I tried putting a return to the call back but I get weird data.. can you show a quick example? Thank you.
@smorhaim Adding a return does nothing because it's just returning it to whatever called your callback within the async context established in your call to connection.query. In short, you can't access the populated $products outside of the callback.
@smorhaim, the call to connection.query returns (almost) immediately. You just left a callback function to be run when the results arrive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.