giannisf
giannisf

Reputation: 2599

Asyncjs parallel, run in loop

I have an array with url's

var urls = ['http://google.com', 'http://example.com', 'http://localhost:300'];

and a function that reads from url

function readUrl(url) {....}

i wan't to run the function for all available urls in the array. Is that possible with asyncjs? or any other suggestion.

Upvotes: 0

Views: 138

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

Is that possible with asyncjs?

yes, it is possible., like this

1.

var async = require('async');
var urls  = ['http://google.com', 'http://amazon.com', 'http://bing.com'];

function readUrl(url, next) {
  // some code  
  next(null, result);
}

urls = urls.map(function(url) {
  return function (next) {
    readUrl(url, next);
  };
});

async.parallel(urls, function(err, res) {
  console.log(err, res);
})

2.

var async = require('async');
var urls = ['http://google.com', 'http://amazon.com', 'http://bing.com'];

function readUrl(url) {
  return true;
}

urls = urls.map(function(url) {
  return function (next) {
    var res = readUrl(url);

    if (res) {
      return next(null, res);
    }

    next('Error');
  };
});

async.parallel(urls, function(err, res) {
  console.log(err, res);
})

Upvotes: 1

Related Questions