Friday, 21 April 2017

node js concurrent requests affect the response

I am getting an array of file ids from a http request(box api) and for each file id ,I in turn make another http request to get one more info.

I have an counter variable 'count' declared.

this is how i am doing it. //result is from first http request

     for(var i=0;i<result.entries.length;i++){

      getStoryID(result.entries[i],accessToken,function(storyid,total){ 
            if(total== result.entries.length){
                    response.send(storyid)
                    })  
         })
      }

function getStoryID is given below:

function getStoryID(files,accessToken,callback){


var options = {
  "method": "GET",
  "hostname": "api.box.com",
  "port": null,
  "path": "/2.0/files/"+files.id+"/metadata/enterprise/boxstoryasset",
  "headers": {
    "authorization": "Bearer "+accessToken
  }
}

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    var result = JSON.parse(body)

        StoryID.push(result.boxstoryid)
        count++
        return callback(StoryID,count)   
  });
});

req.end();

}

I know i have done something terribly wring. For single request it works fine. but for concurrent requests , only one request is being served and other got stuck. I think both request are updating the counter variable at the same time.

I tried to remove the counter variable and try to check the length of the array by removing first element of the array in each callback.but now both requests are getting the same response.

so basically I am not able to handle concurrent requests. Please help me to resolve this.



via user3742114