Sid
Sid

Reputation: 645

Javascript print all the status at a time using request node module

I'm new to javascript and promises, I had a requirement where I need to get the http status of my URL's(i have 10 URL's) all at a time (Not sequentialy). So I wrote below code.

var request = require('request');

var fun = function(i) {
  request('http://myapp' + i + '.com', function(error, response, body) {
    console.log(response && response.statusCode, i);
  });
};

for (i = 0; i < 10; i++) {
  fun(i);
}

but I'm getting status1 then status2 then status3 and so on..... my requirement is to print all the status at one time.

then tried below code

var request = require('request');

var fun = function(myapp) {
  return new Promise(function(resolve, reject) {
    request('http://' + myapp + '.com', function(error, response, body) {
      resolve(response && response.statusCode);
    });
  });
};

for (i = 0; i < 10; i++) {
  fun('myapp' + i).then(function(val1) {
    console.log(val1);
  });
}

but still, I'm getting status1 then status2 then status3 and so on..... Any help is appreciated.

Upvotes: 0

Views: 102

Answers (2)

Nikos M.
Nikos M.

Reputation: 8325

Your code is correct. It executes asynchronously in parallel.

However you are confused into seeing output be printed in sequence (or what looks like sequence) but this is normal, no matter if parallel or synhronous, output (as it is coded will be printed one after the other, maybe not in same order).

if you want to output all at once when finished, do sth like the following:

var request = require('request');
var finished = new Array(10);
var numFinished = 0;

var fun = function(i) {
  request('http://myapp' + i + '.com', function(error, response, body) {
    finished[i] = response && response.statusCode ? response.statusCode : 'No response';
    numFinished++;
  });
};

for (i = 0; i < 10; i++) {
  fun(i);
}

var timer = setTinterval(function(){
   if ( 10 <= numFinished )
   {
      clearInterval(timer);
      console.log(finished.join(',')); // print all at once
   }
}, 500);

Or if you use promises you can do:

var request = require('request');

var fun = function(myapp) {
  return new Promise(function(resolve, reject) {
    request('http://' + myapp + '.com', function(error, response, body) {
       resolve(response && response.statusCode ? response.statusCode : 'No response');
    });
  });
};

var promises = new Array(10);

for (i = 0; i < 10; i++) {
    promises[i] = fun('myapp' + i);

Promise.all(promises).then(function(results){
   console.log(results.join(',')); // print all at once
});

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138267

You could collect all the promises in an array, then use Promise.all on that to get an array of results:

  const promises = [];

  for (i = 0; i < 10; i++) {
    promises.push( fun('myapp' + i));


  Promise.all(promises)
    .then(console.log, console.error);

Upvotes: 2

Related Questions