giannisf giannisf - 5 months ago 10
Node.js Question

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.

Answer

There are several ways to solve this issues, for instance you can use async library 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);
})