javascript - node.js : Variables outside of functions -
i'm new nodejs , trying figure out stuff unfortunately couldn't find information on knowledge.
basicly, want use variable function inside function wich child of main function.
here code :
http.get(url, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { var jsonresult = json.parse(body); (var i=0;i<5;i++) { gameid = jsonresult.gamelist[i].gameid; url = 'http://somesite.com/' + gameid + '/0/token'; http.get(url, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { jsonres = json.parse(body); switch(i) { case 0: var elo0 = jsonres.interestscore; module.exports.elo0 = elo0; break; case 1: var elo1 = jsonres.interestscore; module.exports.elo1 = elo1; break; case 2: var elo2 = jsonres.interestscore; module.exports.elo2 = elo2; break; case 3: var elo3 = jsonres.interestscore; module.exports.elo3 = elo3; break; case 4: var elo4 = jsonres.interestscore; module.exports.elo4 = elo4; break; } }); }).on('error', function(e) { console.log("got error: ", e); }); } }); }).on('error', function(e) { console.log("got error: ", e); });
note didn't include everything, problematic part. want use variable loop inside switch doesn't work.
the problem here referencing i
in switch statement within asynchronous callback. when this, won't value of @ time function created, final value of @ end of loop iteration.
there couple of ways fix - both involve trapping current loop value of in closure later reference callback.
for example:
for (var i=0;i<5;i++) { (function(idx) { gameid = jsonresult.gamelist[idx].gameid; url = 'http://somesite.com/' + gameid + '/0/token'; http.get(url, function(res) { ... res.on('end', function() { jsonres = json.parse(body); switch(idx) { case 0: break; ... } }); ... }); })(i); }
here, anonymous function created each pass through loop , called passing current value of loop counter i
incoming parameter idx
.
another approach (as mentioned in comments above) refactor inner part of loop separate function , call passing necessary context:
function scorehandler(jsonresult, idx) { var gameid = jsonresult.gamelist[idx].gameid; var url = 'http://somesite.com/' + gameid + '/0/token'; http.get(url, function(res) { ... res.on('end', function() { jsonres = json.parse(body); switch (idx) { ... } }); }) .on('error', function(e) { console.log("got error: ", e); }); }
your refactored loop like:
res.on('end', function() { var jsonresult = json.parse(body); (var = 0; < 5; i++) { scorehandler(jsonresult, i); } });
Comments
Post a Comment