Djinnes Djinnes - 2 months ago 6
Node.js Question

Looping a request that returns results in order they were put in

This code is the same structure as my code:

for (var i in UserNameArray)
{
var Urls = "https://some online api"+UserNameArray[i]+"api key";
//the url changes by plugging in the next array value every iteration.
request({
url: Urls,
json: true
}, function (error, response, body) {

if (!error && response.statusCode === 200) {
console.log(body);
}
})
}


It returns a json from the URL correctly, but it's printing it out by which every iterated request returns first. How can I change my code so that it prints out the requests in the order that they were requested? This is important as I will have to traverse the specific JSON with a specific value from UserNameArray.

Answer

Try this one.

Im going trough all of them, and storing the response in an result array (by index). Then when all of them have finished it goes to a final callback where we print them (in order) to the console.

var async =  require('async'); 
var result = [];

async.eachOf(UserNameArray, function(name, i, cb) {

    //the url changes by plugging in the next array value every iteration.
   var Urls = "https://some online api"+UserNameArray[i]+"api key";
  request({
    url: Urls,
    json: true
  }, function (error, response, body) {

    // checking if something went wrong..    
    if (error) return cb(error);

    if (!error && response.statusCode === 200) {

        // storing the response to our result array
        result[i] = body;
        // do a callback, telling that we are done here
        cb();
    }

  })

}, function(err) {

        // all done.

        // lets print the errors if something went wrong
        if (err) console.error(err.message);

        // lets print our results
        for(var i=0; i<result.length; i++) {
        console.log(result[i]);
    }
});
Comments