json - JavaScript Closures, Really simple example with jsFiddle -
i'm pulling hair out trying understand javascript closures. i'm looking closely @ this example. actual code in node.js don't think that's major issue (except error codes..)
here's slimmed down code:
var jsonsymbols = { "id5": "wfc", "id4": "amzn", "id3": "baba", "id2": "yhoo", "id1": "goog", "id0": "aapl" }; // assume unknown number of stock symbols.. var count = 0; var outputprices = {}; (key in jsonsymbols) { outputprices['newid' + count]['price'] = get_price(jsonsymbols[key], count, function() { console.log(" dummy function"); // callback function used when looking 1 stock. }); count++; } console.log("\ncount = " + count); console.log("\noutput = " + json.stringify(outputprices)); function get_price(symbol, countindex, callback) { setinterval(function() { // nothing... actual function makes http call server // , stock price lookup. can 1 stock @ time, // hence repeated calls. }, 1000); return 124.12; callback(); };
(hmmm. i'm new snippet stuff. i've created jsfiddle ) current error code uncaught typeerror: cannot set property 'price' of undefined
i'm missing stupid. there way have cake , drink beer too? i'm learning how asynchronous stuff works, unfortunately have difficult time beginning learning process in pure abstract concepts. need concrete example start, , can extrapolate abstract.
anybody been here before? why doesn't work? thx.
Comments
Post a Comment