1

I am looking for a module in Node.js that will run a function for each item in an array but pause execution of the next item in the array until a value is returned for the last.

I have async.concatSeries() running a series of request functions.

looks like this

var foo = [id,id,id];
function bar(){//do something then return value}
async.concatSeries(foo, bar, function(err, result){//log result});

I would like to return all of these in the same order as the array. Any help would be great, thanks!

2
  • How is it an 'async' function when you want it to execute in sequential order? Commented Jan 24, 2014 at 18:44
  • @grebneke, as mentioned in a comment to an answer below, sequential is not the same as synchronous. Asynchronous functions can be executed in sequence, and not be synchronous since the sequence spans multiple ticks. Commented Jan 25, 2014 at 3:29

2 Answers 2

3

If you pause to wait for previous results, you are working synchronously. Just use Array.map():

results = [1, 2, 3].map( function(element, index) {
    return element * 2;
});

// results = [2, 4, 6]
Sign up to request clarification or add additional context in comments.

2 Comments

This is conflating synchronous with sequential. Functions may be processed in sequence across multiple ticks, which is not synchronous.
This was tremendous! Thank you for the help.
1

There are times when it may be a good idea to run tasks in sequence, or batch them to limit outgoing connections etc.

The most well known library is async. With it your code would look like:

var async = require('async');

// Some array of data.
var ids = [0, 1, 2, 3, 4, 5];

// Async function applying to one element.
function getUser(id, callback) {
    // A call to a datastore for example.
    if (err) {
        return callback(err);
    }

    callback(null, user);
}

async.mapSeries(ids, getUser, function (err, users) {
    // You now have an error or an array of results. The array will be in the
    // same order as the ids.
});

You can also use async.map for parallel execution, and async.mapLimit for parallel execution with a limited number the ids used at any given time.

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.