MonsterWimp757
MonsterWimp757

Reputation: 1217

Node.js - looking for async function

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!

Upvotes: 1

Views: 255

Answers (2)

qubyte
qubyte

Reputation: 17748

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.

Upvotes: 1

salezica
salezica

Reputation: 76899

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]

Upvotes: 3

Related Questions