node.js - Getting original request object during multiple asynchronous calls in nodejs-request -
i have multiple http requests in nodejs app each returns word of sentence. replies come @ different times, i'm saving them in dictionary, key being original sentence's word index. problem is, when access request object, last one.
var completed_requests = 0; sentence = req.query.sentence; sentence = "sentence translated" responses=[]; words = sentence.split(" "); for(j=0;j<words.length;j++){ var word = words[j]; var data={ word:word }; var options = { url: 'example.com', form:data, index:j }; request.post(options, function(err,httpresponse,body){ options = options; if(!err){ responses.push({options.index: body}); completed_requests+=1; if(completed_requests==words.length){ var a=""; for(var k=0;k<words.length;k++){ a+=responses[k]+" "; } res.render('pages/index', { something: }); } } else{ //err } }); }
basically, when access object.index
object, object returned isn't 1 used original request, last 1 (for reason). how should resolve this?
when take @ how code evaluated javascript due it's async nature in node.js problem becomes obvious:
- for first word loop
for(j=0;j<words.length;j++){
executed. - the value of
j
assignedoptions.index
. loop runoptions.index
has value0
. request.post(options, function(err,httpresponse,body){
executed callback handler invoked later.- for first word loop
for(j=0;j<words.length;j++){
executed. - the value of
j
assignedoptions.index
.options.index
has value1
. request.post(options, function(err,httpresponse,body){
executed callback handler invoked later.
the problem becomes obvious since no new options
objects created value of j
assigned options.index
in every loop run. when first callback handler invoked options.index
has value words.length - 1
.
to fix problem wrap creating options object in function executerequest
var completed_requests = 0; sentence = req.query.sentence; sentence = "sentence translated" responses=[]; words = sentence.split(" "); for(j=0;j<words.length;j++){ var word = words[j]; var data={ word:word }; function executerequest(url, form, index) { var options = { url: url, form: form, index: index }; request.post(options, function(err,httpresponse,body){ // options = options; superfluous if(!err){ responses.push({ [index]: body}); completed_requests+=1; if(completed_requests==words.length){ var a=""; for(var k=0;k<words.length;k++){ a+=responses[k]+" "; } res.render('pages/index', { something: }); } } else{ //err } }); } executerequest('example.com', data, j); }
a read scoping , hoisting in javascript can found here http://www.adequatelygood.com/javascript-scoping-and-hoisting.html
Comments
Post a Comment