I'm pulling my hair out trying to understand javascript closures. I'm looking closely at this example. My actual code is in node.js but I don't think that's a major issue (except for error codes..)
Here's my slimmed down code:
var jsonsymbols = {
"id5": "WFC",
"id4": "AMZN",
"id3": "BABA",
"id2": "YHOO",
"id1": "GOOG",
"id0": "AAPL"
};
// assume an unknown number of stock symbols..
var count = 0;
var outputPrices = {};
for (key in jsonsymbols) {
outputPrices['newid' + count]['price'] = get_price(jsonsymbols[key], count, function() {
console.log(" Dummy function"); // callback function is used when looking up only one stock.
});
count++;
}
console.log("\ncount = " + count);
console.log("\noutput = " + JSON.stringify(outputPrices));
function get_price(symbol, countindex, callback) {
setInterval(function() {
// do nothing... The actual function makes a http call to another server
// and does stock price lookup. We can only look up one stock at a time,
// hence the repeated calls.
}, 1000);
return 124.12;
callback();
};
(hmmm. I'm new to this snippet stuff. I've also created a jsfiddle ) Current error code is Uncaught TypeError: Cannot set property 'price' of undefined
I'm obviously missing something stupid. Is there any way to have my cake and drink beer too? I'm learning how this asynchronous stuff works, unfortunately I have a very difficult time beginning the learning process in pure abstract concepts. I need a concrete example to start, and from that I can extrapolate back to the abstract.
Anybody been here before? Why doesn't this work? thx.