Voora Tarun Voora Tarun - 6 months ago 7
Node.js Question

Nodejs Identify output of asyntasks

I am new to nodejs, I am making multiple get requests with request nodejs api,
with this, I am unable to figure out output of a particular request. How to identify the response of each request individually ? I am using for loop to send multiple requests. If i use recursion, it becomes again synchronous, i just have to separate request with response that too asynchronous. Is it possible ?

In the below code variable 'i' is replace by last iteration .

var list = [ 'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%20Mobiles%20with%20best&phrase2=Mobiles%20with%20best',
'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%2520Mobiles%2520with%2520best&phrase2=what%20is%20a%20processor']

function ss(list){
for(var i in list) {
request(list[i], function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log( i + " " +body);
}
})
}
}

Answer

You can use the async library to perform async requests. Spefically, you can use async.each or async.eachSeries.

The difference between the 2 of them is that each will run all the requests in parallel, just as the for loop does, but will retain context, as opposed to eachSeries which will run the requests one at a time(second iteration will begin only when you called the callback function of the first). Also - there are other options for more specific use cases(like eachLimit for instance).

example code using each:

var list = [ 'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%20Mobiles%20with%20best&phrase2=Mobiles%20with%20best',
      'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%2520Mobiles%2520with%2520best&phrase2=what%20is%20a%20processor']

function ss(list){
    async.each(list, function(listItem, next) {
        request(listItem, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log( listItem + " " +body);
            }

            next();
            return;
        })
    },
    //finally mehtod
    function(err) {
        console.log('all iterations completed.')
    })
}