简体   繁体   中英

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!

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM