1

I have this array with rest-api paths:

var paths = ['path1','path2','path3'];

I want to create an array with results from each path. In this case I instead use 'http://www.google.com/index.html' instead of 'path'

exports.test = function(req, res){

  var paths = ['path1','path2','path3'];

  var resultArr = [];
  async.each(paths, function(path, cb){

    console.log('collecting data from: ' + path);
    http.get('http://www.google.com/index.html', function(result){

      resultArr.push(result);
      console.log('Done collecting data from: ' + path);
      cb();
    });

  }, function(){
    console.log('Done collecting data from all paths');
    res.status(200).send('hello');
  });
};

This logs:

Starting server at 127.0.0.1:5000
collecting data from: path1
collecting data from: path2
collecting data from: path3
Done collecting data from: path2
Done collecting data from: path1
Done collecting data from: path3
Done collecting data from all paths
GET /test 304 128.752 ms - -

It's not waiting for a a call to complete. I want to get the results in series, one by one. What am I doing wrong?

2
  • 1
    You code behave correctly, what are you expecting to happen here ? Commented Dec 6, 2015 at 14:56
  • "Note, that since this function applies iterator to each item in parallel, there is no guarantee that the iterator functions will complete in order." - npmjs.com/package/async#each Commented Dec 6, 2015 at 15:00

1 Answer 1

2

Change each to eachSeries.

exports.test = function(req, res){

  var paths = ['path1','path2','path3'];

  var resultArr = [];
  async.eachSeries(paths, function(path, cb){

    console.log('collecting data from: ' + path);
    http.get('http://www.google.com/index.html', function(result){

      resultArr.push(result);
      console.log('Done collecting data from: ' + path);
      cb();
    });

  }, function(){
    console.log('Done collecting data from all paths');
    res.status(200).send('hello');
  });
};

This logs:

collecting data from: path1
Done collecting data from: path1
collecting data from: path2
Done collecting data from: path2
collecting data from: path3
Done collecting data from: path3
Done collecting data from all paths
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.