Control Flow

A collection of async functions for controlling the flow through a script.

Source:

Methods

(static) applyEach(fns, …argsopt, callbackopt) → {function}

import applyEach from 'async/applyEach';

Applies the provided arguments to each function in the array, calling callback after all functions have completed. If you only provide the first argument, fns, then it will return a function which lets you pass in the arguments as if it were a single function call. If more arguments are provided, callback is required while args is still optional.

Parameters:
Name Type Description
fns Array | Iterable | Object

A collection of AsyncFunctions to all call with the same arguments

args * <optional>

any number of separate arguments to pass to the function.

callback function <optional>

the final argument should be the callback, called when all functions have completed processing.

Returns:
  • If only the first argument, fns, is provided, it will return a function which lets you pass in the arguments as if it were a single function call. The signature is (..args, callback). If invoked with any arguments, callback is required.
Type
function
Example
async.applyEach([enableSearch, updateSchema], 'bucket', callback);

// partial application example:
async.each(
    buckets,
    async.applyEach([enableSearch, updateSchema]),
    callback
);
Source:

(static) applyEachSeries(fns, …argsopt, callbackopt) → {function}

import applyEachSeries from 'async/applyEachSeries';

The same as applyEach but runs only a single async operation at a time.

Parameters:
Name Type Description
fns Array | Iterable | Object

A collection of AsyncFunctions to all call with the same arguments

args * <optional>

any number of separate arguments to pass to the function.

callback function <optional>

the final argument should be the callback, called when all functions have completed processing.

Returns:
  • If only the first argument is provided, it will return a function which lets you pass in the arguments as if it were a single function call.
Type
function
Source:
See:

(static) auto(tasks, concurrencyopt, callbackopt)

import auto from 'async/auto';

Determines the best order for running the AsyncFunctions in tasks, based on their requirements. Each function can optionally depend on other functions being completed first, and each function is run as soon as its requirements are satisfied.

If any of the AsyncFunctions pass an error to their callback, the auto sequence will stop. Further tasks will not execute (so any other functions depending on it will not run), and the main callback is immediately called with the error.

AsyncFunctions also receive an object containing the results of functions which have completed so far as the first argument, if they have dependencies. If a task function has no dependencies, it will only be passed a callback.

Parameters:
Name Type Default Description
tasks Object

An object. Each of its properties is either a function or an array of requirements, with the AsyncFunction itself the last item in the array. The object's key of a property serves as the name of the task defined by that property, i.e. can be used when specifying requirements for other tasks. The function receives one or two arguments:

  • a results object, containing the results of the previously executed functions, only passed if the task has any dependencies,
  • a callback(err, result) function, which must be called when finished, passing an error (which can be null) and the result of the function's execution.
concurrency number <optional> Infinity

An optional integer for determining the maximum number of tasks that can be run in parallel. By default, as many as possible.

callback function <optional>

An optional callback which is called when all the tasks have been completed. It receives the err argument if any tasks pass an error to their callback. Results are always returned; however, if an error occurs, no further tasks will be performed, and the results object will only contain partial results. Invoked with (err, results).

Returns:

undefined

Example
async.auto({
    // this function will just be passed a callback
    readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
    showData: ['readData', function(results, cb) {
        // results.readData is the file's contents
        // ...
    }]
}, callback);

async.auto({
    get_data: function(callback) {
        console.log('in get_data');
        // async code to get some data
        callback(null, 'data', 'converted to array');
    },
    make_folder: function(callback) {
        console.log('in make_folder');
        // async code to create a directory to store a file in
        // this is run at the same time as getting the data
        callback(null, 'folder');
    },
    write_file: ['get_data', 'make_folder', function(results, callback) {
        console.log('in write_file', JSON.stringify(results));
        // once there is some data and the directory exists,
        // write the data to a file in the directory
        callback(null, 'filename');
    }],
    email_link: ['write_file', function(results, callback) {
        console.log('in email_link', JSON.stringify(results));
        // once the file is written let's email a link to it...
        // results.write_file contains the filename returned by write_file.
        callback(null, {'file':results.write_file, 'email':'user@example.com'});
    }]
}, function(err, results) {
    console.log('err = ', err);
    console.log('results = ', results);
});
Source:

(static) autoInject(tasks, callbackopt)

import autoInject from 'async/autoInject';

A dependency-injected version of the async.auto function. Dependent tasks are specified as parameters to the function, after the usual callback parameter, with the parameter names matching the names of the tasks it depends on. This can provide even more readable task graphs which can be easier to maintain.

If a final callback is specified, the task results are similarly injected, specified as named parameters after the initial error parameter.

The autoInject function is purely syntactic sugar and its semantics are otherwise equivalent to async.auto.

Parameters:
Name Type Description
tasks Object

An object, each of whose properties is an AsyncFunction of the form 'func([dependencies...], callback). The object's key of a property serves as the name of the task defined by that property, i.e. can be used when specifying requirements for other tasks.

  • The callback parameter is a callback(err, result) which must be called when finished, passing an error (which can be null) and the result of the function's execution. The remaining parameters name other tasks on which the task is dependent, and the results from those tasks are the arguments of those parameters.
callback function <optional>

An optional callback which is called when all the tasks have been completed. It receives the err argument if any tasks pass an error to their callback, and a results object with any completed task results, similar to auto.

Example
//  The example from `auto` can be rewritten as follows:
async.autoInject({
    get_data: function(callback) {
        // async code to get some data
        callback(null, 'data', 'converted to array');
    },
    make_folder: function(callback) {
        // async code to create a directory to store a file in
        // this is run at the same time as getting the data
        callback(null, 'folder');
    },
    write_file: function(get_data, make_folder, callback) {
        // once there is some data and the directory exists,
        // write the data to a file in the directory
        callback(null, 'filename');
    },
    email_link: function(write_file, callback) {
        // once the file is written let's email a link to it...
        // write_file contains the filename returned by write_file.
        callback(null, {'file':write_file, 'email':'user@example.com'});
    }
}, function(err, results) {
    console.log('err = ', err);
    console.log('email_link = ', results.email_link);
});

// If you are using a JS minifier that mangles parameter names, `autoInject`
// will not work with plain functions, since the parameter names will be
// collapsed to a single letter identifier.  To work around this, you can
// explicitly specify the names of the parameters your task function needs
// in an array, similar to Angular.js dependency injection.

// This still has an advantage over plain `auto`, since the results a task
// depends on are still spread into arguments.
async.autoInject({
    //...
    write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
        callback(null, 'filename');
    }],
    email_link: ['write_file', function(write_file, callback) {
        callback(null, {'file':write_file, 'email':'user@example.com'});
    }]
    //...
}, function(err, results) {
    console.log('err = ', err);
    console.log('email_link = ', results.email_link);
});
Source:
See:

(static) cargo(worker, payloadopt) → {CargoObject}

import cargo from 'async/cargo';

Creates a cargo object with the specified payload. Tasks added to the cargo will be processed altogether (up to the payload limit). If the worker is in progress, the task is queued until it becomes available. Once the worker has completed some tasks, each callback of those tasks is called. Check out these animations for how cargo and queue work.

While queue passes only one task to one of a group of workers at a time, cargo passes an array of tasks to a single worker, repeating when the worker is finished.

Parameters:
Name Type Default Description
worker AsyncFunction

An asynchronous function for processing an array of queued tasks. Invoked with (tasks, callback).

payload number <optional> Infinity

An optional integer for determining how many tasks should be processed per round; if omitted, the default is unlimited.

Returns:

A cargo object to manage the tasks. Callbacks can attached as certain properties to listen for specific events during the lifecycle of the cargo and inner queue.

Type
CargoObject
Example
// create a cargo object with payload 2
var cargo = async.cargo(function(tasks, callback) {
    for (var i=0; i<tasks.length; i++) {
        console.log('hello ' + tasks[i].name);
    }
    callback();
}, 2);

// add some items
cargo.push({name: 'foo'}, function(err) {
    console.log('finished processing foo');
});
cargo.push({name: 'bar'}, function(err) {
    console.log('finished processing bar');
});
cargo.push({name: 'baz'}, function(err) {
    console.log('finished processing baz');
});
Source:
See:

(static) compose(…functions) → {function}

import compose from 'async/compose';

Creates a function which is a composition of the passed asynchronous functions. Each function consumes the return value of the function that follows. Composing functions f(), g(), and h() would produce the result of f(g(h())), only this version uses callbacks to obtain the return values.

Each function is executed with the this binding of the composed function.

Parameters:
Name Type Description
functions AsyncFunction

the asynchronous functions to compose

Returns:

an asynchronous function that is the composed asynchronous functions

Type
function
Example
function add1(n, callback) {
    setTimeout(function () {
        callback(null, n + 1);
    }, 10);
}

function mul3(n, callback) {
    setTimeout(function () {
        callback(null, n * 3);
    }, 10);
}

var add1mul3 = async.compose(mul3, add1);
add1mul3(4, function (err, result) {
    // result now equals 15
});
Source:

(static) doDuring(fn, test, callbackopt)

import doDuring from 'async/doDuring';

The post-check version of during. To reflect the difference in the order of operations, the arguments test and fn are switched.

Also a version of doWhilst with asynchronous test function.

Parameters:
Name Type Description
fn AsyncFunction

An async function which is called each time test passes. Invoked with (callback).

test AsyncFunction

asynchronous truth test to perform before each execution of fn. Invoked with (...args, callback), where ...args are the non-error args from the previous callback of fn.

callback function <optional>

A callback which is called after the test function has failed and repeated execution of fn has stopped. callback will be passed an error if one occurred, otherwise null.

Source:
See:

(static) doUntil(iteratee, test, callbackopt)

import doUntil from 'async/doUntil';

Like 'doWhilst', except the test is inverted. Note the argument ordering differs from until.

Parameters:
Name Type Description
iteratee AsyncFunction

An async function which is called each time test fails. Invoked with (callback).

test function

synchronous truth test to perform after each execution of iteratee. Invoked with any non-error callback results of iteratee.

callback function <optional>

A callback which is called after the test function has passed and repeated execution of iteratee has stopped. callback will be passed an error and any arguments passed to the final iteratee's callback. Invoked with (err, [results]);

Source:
See:

(static) doWhilst(iteratee, test, callbackopt)

import doWhilst from 'async/doWhilst';

The post-check version of whilst. To reflect the difference in the order of operations, the arguments test and iteratee are switched.

doWhilst is to whilst as do while is to while in plain JavaScript.

Parameters:
Name Type Description
iteratee AsyncFunction

A function which is called each time test passes. Invoked with (callback).

test function

synchronous truth test to perform after each execution of iteratee. Invoked with any non-error callback results of iteratee.

callback function <optional>

A callback which is called after the test function has failed and repeated execution of iteratee has stopped. callback will be passed an error and any arguments passed to the final iteratee's callback. Invoked with (err, [results]);

Source:
See:

(static) during(test, fn, callbackopt)

import during from 'async/during';

Like whilst, except the test is an asynchronous function that is passed a callback in the form of function (err, truth). If error is passed to test or fn, the main callback is immediately called with the value of the error.

Parameters:
Name Type Description
test AsyncFunction

asynchronous truth test to perform before each execution of fn. Invoked with (callback).

fn AsyncFunction

An async function which is called each time test passes. Invoked with (callback).

callback function <optional>

A callback which is called after the test function has failed and repeated execution of fn has stopped. callback will be passed an error, if one occurred, otherwise null.

Example
var count = 0;

async.during(
    function (callback) {
        return callback(null, count < 5);
    },
    function (callback) {
        count++;
        setTimeout(callback, 1000);
    },
    function (err) {
        // 5 seconds have passed
    }
);
Source:
See:

(static) forever(fn, errbackopt)

import forever from 'async/forever';

Calls the asynchronous function fn with a callback parameter that allows it to call itself again, in series, indefinitely. If an error is passed to the callback then errback is called with the error, and execution stops, otherwise it will never be called.

Parameters:
Name Type Description
fn AsyncFunction

an async function to call repeatedly. Invoked with (next).

errback function <optional>

when fn passes an error to it's callback, this function will be called, and execution stops. Invoked with (err).

Example
async.forever(
    function(next) {
        // next is suitable for passing to things that need a callback(err [, whatever]);
        // it will result in this function being called again.
    },
    function(err) {
        // if next is called with a value in its first parameter, it will appear
        // in here as 'err', and execution will stop.
    }
);
Source:

(static) parallel(tasks, callbackopt)

import parallel from 'async/parallel';

Run the tasks collection of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback, the main callback is immediately called with the value of the error. Once the tasks have completed, the results are passed to the final callback as an array.

Note: parallel is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded.

Hint: Use reflect to continue the execution of other tasks when a task fails.

It is also possible to use an object instead of an array. Each property will be run as a function and the results will be passed to the final callback as an object instead of an array. This can be a more readable way of handling results from async.parallel.

Parameters:
Name Type Description
tasks Array | Iterable | Object

A collection of async functions to run. Each async function can complete with any number of optional result values.

callback function <optional>

An optional callback to run once all the functions have completed successfully. This function gets a results array (or object) containing all the result arguments passed to the task callbacks. Invoked with (err, results).

Example
async.parallel([
    function(callback) {
        setTimeout(function() {
            callback(null, 'one');
        }, 200);
    },
    function(callback) {
        setTimeout(function() {
            callback(null, 'two');
        }, 100);
    }
],
// optional callback
function(err, results) {
    // the results array will equal ['one','two'] even though
    // the second function had a shorter timeout.
});

// an example using an object instead of an array
async.parallel({
    one: function(callback) {
        setTimeout(function() {
            callback(null, 1);
        }, 200);
    },
    two: function(callback) {
        setTimeout(function() {
            callback(null, 2);
        }, 100);
    }
}, function(err, results) {
    // results is now equals to: {one: 1, two: 2}
});
Source:

(static) parallelLimit(tasks, limit, callbackopt)

import parallelLimit from 'async/parallelLimit';

The same as parallel but runs a maximum of limit async operations at a time.

Parameters:
Name Type Description
tasks Array | Iterable | Object

A collection of async functions to run. Each async function can complete with any number of optional result values.

limit number

The maximum number of async operations at a time.

callback function <optional>

An optional callback to run once all the functions have completed successfully. This function gets a results array (or object) containing all the result arguments passed to the task callbacks. Invoked with (err, results).

Source:
See:

(static) priorityQueue(worker, concurrency) → {QueueObject}

import priorityQueue from 'async/priorityQueue';

The same as async.queue only tasks are assigned a priority and completed in ascending priority order.

Parameters:
Name Type Description
worker AsyncFunction

An async function for processing a queued task. If you want to handle errors from an individual task, pass a callback to q.push(). Invoked with (task, callback).

concurrency number

An integer for determining how many worker functions should be run in parallel. If omitted, the concurrency defaults to 1. If the concurrency is 0, an error is thrown.

Returns:

A priorityQueue object to manage the tasks. There are two differences between queue and priorityQueue objects:

  • push(task, priority, [callback]) - priority should be a number. If an array of tasks is given, all tasks will be assigned the same priority.
  • The unshift method was removed.
Type
QueueObject
Source:
See:

(static) queue(worker, concurrencyopt) → {QueueObject}

import queue from 'async/queue';

Creates a queue object with the specified concurrency. Tasks added to the queue are processed in parallel (up to the concurrency limit). If all workers are in progress, the task is queued until one becomes available. Once a worker completes a task, that task's callback is called.

Parameters:
Name Type Default Description
worker AsyncFunction

An async function for processing a queued task. If you want to handle errors from an individual task, pass a callback to q.push(). Invoked with (task, callback).

concurrency number <optional> 1

An integer for determining how many worker functions should be run in parallel. If omitted, the concurrency defaults to 1. If the concurrency is 0, an error is thrown.

Returns:

A queue object to manage the tasks. Callbacks can attached as certain properties to listen for specific events during the lifecycle of the queue.

Type
QueueObject
Example
// create a queue object with concurrency 2
var q = async.queue(function(task, callback) {
    console.log('hello ' + task.name);
    callback();
}, 2);

// assign a callback
q.drain = function() {
    console.log('all items have been processed');
};

// add some items to the queue
q.push({name: 'foo'}, function(err) {
    console.log('finished processing foo');
});
q.push({name: 'bar'}, function (err) {
    console.log('finished processing bar');
});

// add some items to the queue (batch-wise)
q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
    console.log('finished processing item');
});

// add some items to the front of the queue
q.unshift({name: 'bar'}, function (err) {
    console.log('finished processing bar');
});
Source:

(static) race(tasks, callback)

import race from 'async/race';

Runs the tasks array of functions in parallel, without waiting until the previous function has completed. Once any of the tasks complete or pass an error to its callback, the main callback is immediately called. It's equivalent to Promise.race().

Parameters:
Name Type Description
tasks Array

An array containing async functions to run. Each function can complete with an optional result value.

callback function

A callback to run once any of the functions have completed. This function gets an error or result from the first function that completed. Invoked with (err, result).

Returns:

undefined

Example
async.race([
    function(callback) {
        setTimeout(function() {
            callback(null, 'one');
        }, 200);
    },
    function(callback) {
        setTimeout(function() {
            callback(null, 'two');
        }, 100);
    }
],
// main callback
function(err, result) {
    // the result will be equal to 'two' as it finishes earlier
});
Source:

(static) retry(optsopt, task, callbackopt)

import retry from 'async/retry';

Attempts to get a successful response from task no more than times times before returning an error. If the task is successful, the callback will be passed the result of the successful task. If all attempts fail, the callback will be passed the error and result (if any) of the final attempt.

Parameters:
Name Type Default Description
opts Object | number <optional> {times: 5, interval: 0}| 5

Can be either an object with times and interval or a number.

  • times - The number of attempts to make before giving up. The default is 5.
  • interval - The time to wait between retries, in milliseconds. The default is 0. The interval may also be specified as a function of the retry count (see example).
  • errorFilter - An optional synchronous function that is invoked on erroneous result. If it returns true the retry attempts will continue; if the function returns false the retry flow is aborted with the current attempt's error and result being returned to the final callback. Invoked with (err).
  • If opts is a number, the number specifies the number of times to retry, with the default interval of 0.
task AsyncFunction

An async function to retry. Invoked with (callback).

callback function <optional>

An optional callback which is called when the task has succeeded, or after the final failed attempt. It receives the err and result arguments of the last attempt at completing the task. Invoked with (err, results).

Example
// The `retry` function can be used as a stand-alone control flow by passing
// a callback, as shown below:

// try calling apiMethod 3 times
async.retry(3, apiMethod, function(err, result) {
    // do something with the result
});

// try calling apiMethod 3 times, waiting 200 ms between each retry
async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
    // do something with the result
});

// try calling apiMethod 10 times with exponential backoff
// (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
async.retry({
  times: 10,
  interval: function(retryCount) {
    return 50 * Math.pow(2, retryCount);
  }
}, apiMethod, function(err, result) {
    // do something with the result
});

// try calling apiMethod the default 5 times no delay between each retry
async.retry(apiMethod, function(err, result) {
    // do something with the result
});

// try calling apiMethod only when error condition satisfies, all other
// errors will abort the retry control flow and return to final callback
async.retry({
  errorFilter: function(err) {
    return err.message === 'Temporary error'; // only retry on a specific error
  }
}, apiMethod, function(err, result) {
    // do something with the result
});

// to retry individual methods that are not as reliable within other
// control flow functions, use the `retryable` wrapper:
async.auto({
    users: api.getUsers.bind(api),
    payments: async.retryable(3, api.getPayments.bind(api))
}, function(err, results) {
    // do something with the results
});
Source:
See:

(static) retryable(optsopt, task) → {AsyncFunction}

import retryable from 'async/retryable';

A close relative of retry. This method wraps a task and makes it retryable, rather than immediately calling it with retries.

Parameters:
Name Type Default Description
opts Object | number <optional> {times: 5, interval: 0}| 5

optional options, exactly the same as from retry

task AsyncFunction

the asynchronous function to wrap. This function will be passed any arguments passed to the returned wrapper. Invoked with (...args, callback).

Returns:

The wrapped function, which when invoked, will retry on an error, based on the parameters specified in opts. This function will accept the same parameters as task.

Type
AsyncFunction
Example
async.auto({
    dep1: async.retryable(3, getFromFlakyService),
    process: ["dep1", async.retryable(3, function (results, cb) {
        maybeProcessData(results.dep1, cb);
    })]
}, callback);
Source:
See:

(static) seq(…functions) → {function}

import seq from 'async/seq';

Version of the compose function that is more natural to read. Each function consumes the return value of the previous function. It is the equivalent of compose with the arguments reversed.

Each function is executed with the this binding of the composed function.

Parameters:
Name Type Description
functions AsyncFunction

the asynchronous functions to compose

Returns:

a function that composes the functions in order

Type
function
Example
// Requires lodash (or underscore), express3 and dresende's orm2.
// Part of an app, that fetches cats of the logged user.
// This example uses `seq` function to avoid overnesting and error
// handling clutter.
app.get('/cats', function(request, response) {
    var User = request.models.User;
    async.seq(
        _.bind(User.get, User),  // 'User.get' has signature (id, callback(err, data))
        function(user, fn) {
            user.getCats(fn);      // 'getCats' has signature (callback(err, data))
        }
    )(req.session.user_id, function (err, cats) {
        if (err) {
            console.error(err);
            response.json({ status: 'error', message: err.message });
        } else {
            response.json({ status: 'ok', message: 'Cats found', data: cats });
        }
    });
});
Source:
See:

(static) series(tasks, callbackopt)

import series from 'async/series';

Run the functions in the tasks collection in series, each one running once the previous function has completed. If any functions in the series pass an error to its callback, no more functions are run, and callback is immediately called with the value of the error. Otherwise, callback receives an array of results when tasks have completed.

It is also possible to use an object instead of an array. Each property will be run as a function, and the results will be passed to the final callback as an object instead of an array. This can be a more readable way of handling results from async.series.

Note that while many implementations preserve the order of object properties, the ECMAScript Language Specification explicitly states that

The mechanics and order of enumerating the properties is not specified.

So if you rely on the order in which your series of functions are executed, and want this to work on all platforms, consider using an array.

Parameters:
Name Type Description
tasks Array | Iterable | Object

A collection containing async functions to run in series. Each function can complete with any number of optional result values.

callback function <optional>

An optional callback to run once all the functions have completed. This function gets a results array (or object) containing all the result arguments passed to the task callbacks. Invoked with (err, result).

Example
async.series([
    function(callback) {
        // do some stuff ...
        callback(null, 'one');
    },
    function(callback) {
        // do some more stuff ...
        callback(null, 'two');
    }
],
// optional callback
function(err, results) {
    // results is now equal to ['one', 'two']
});

async.series({
    one: function(callback) {
        setTimeout(function() {
            callback(null, 1);
        }, 200);
    },
    two: function(callback){
        setTimeout(function() {
            callback(null, 2);
        }, 100);
    }
}, function(err, results) {
    // results is now equal to: {one: 1, two: 2}
});
Source:

(static) times(n, iteratee, callback)

import times from 'async/times';

Calls the iteratee function n times, and accumulates results in the same manner you would use with map.

Parameters:
Name Type Description
n number

The number of times to run the function.

iteratee AsyncFunction

The async function to call n times. Invoked with the iteration index and a callback: (n, next).

callback function

see map.

Example
// Pretend this is some complicated async factory
var createUser = function(id, callback) {
    callback(null, {
        id: 'user' + id
    });
};

// generate 5 users
async.times(5, function(n, next) {
    createUser(n, function(err, user) {
        next(err, user);
    });
}, function(err, users) {
    // we should now have 5 users
});
Source:
See:

(static) timesLimit(count, limit, iteratee, callback)

import timesLimit from 'async/timesLimit';

The same as times but runs a maximum of limit async operations at a time.

Parameters:
Name Type Description
count number

The number of times to run the function.

limit number

The maximum number of async operations at a time.

iteratee AsyncFunction

The async function to call n times. Invoked with the iteration index and a callback: (n, next).

callback function

see async.map.

Source:
See:

(static) timesSeries(n, iteratee, callback)

import timesSeries from 'async/timesSeries';

The same as times but runs only a single async operation at a time.

Parameters:
Name Type Description
n number

The number of times to run the function.

iteratee AsyncFunction

The async function to call n times. Invoked with the iteration index and a callback: (n, next).

callback function

see map.

Source:
See:

(static) tryEach(tasks, callbackopt)

import tryEach from 'async/tryEach';

It runs each task in series but stops whenever any of the functions were successful. If one of the tasks were successful, the callback will be passed the result of the successful task. If all tasks fail, the callback will be passed the error and result (if any) of the final attempt.

Parameters:
Name Type Description
tasks Array | Iterable | Object

A collection containing functions to run, each function is passed a callback(err, result) it must call on completion with an error err (which can be null) and an optional result value.

callback function <optional>

An optional callback which is called when one of the tasks has succeeded, or all have failed. It receives the err and result arguments of the last attempt at completing the task. Invoked with (err, results).

Example
async.tryEach([
    function getDataFromFirstWebsite(callback) {
        // Try getting the data from the first website
        callback(err, data);
    },
    function getDataFromSecondWebsite(callback) {
        // First website failed,
        // Try getting the data from the backup website
        callback(err, data);
    }
],
// optional callback
function(err, results) {
    Now do something with the data.
});
Source:

(static) until(test, iteratee, callbackopt)

import until from 'async/until';

Repeatedly call iteratee until test returns true. Calls callback when stopped, or an error occurs. callback will be passed an error and any arguments passed to the final iteratee's callback.

The inverse of whilst.

Parameters:
Name Type Description
test function

synchronous truth test to perform before each execution of iteratee. Invoked with ().

iteratee AsyncFunction

An async function which is called each time test fails. Invoked with (callback).

callback function <optional>

A callback which is called after the test function has passed and repeated execution of iteratee has stopped. callback will be passed an error and any arguments passed to the final iteratee's callback. Invoked with (err, [results]);

Source:
See:

(static) waterfall(tasks, callbackopt)

import waterfall from 'async/waterfall';

Runs the tasks array of functions in series, each passing their results to the next in the array. However, if any of the tasks pass an error to their own callback, the next function is not executed, and the main callback is immediately called with the error.

Parameters:
Name Type Description
tasks Array

An array of async functions to run. Each function should complete with any number of result values. The result values will be passed as arguments, in order, to the next task.

callback function <optional>

An optional callback to run once all the functions have completed. This will be passed the results of the last task's callback. Invoked with (err, [results]).

Returns:

undefined

Example
async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
        // arg1 now equals 'one' and arg2 now equals 'two'
        callback(null, 'three');
    },
    function(arg1, callback) {
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    // result now equals 'done'
});

// Or, with named functions:
async.waterfall([
    myFirstFunction,
    mySecondFunction,
    myLastFunction,
], function (err, result) {
    // result now equals 'done'
});
function myFirstFunction(callback) {
    callback(null, 'one', 'two');
}
function mySecondFunction(arg1, arg2, callback) {
    // arg1 now equals 'one' and arg2 now equals 'two'
    callback(null, 'three');
}
function myLastFunction(arg1, callback) {
    // arg1 now equals 'three'
    callback(null, 'done');
}
Source:

(static) whilst(test, iteratee, callbackopt)

import whilst from 'async/whilst';

Repeatedly call iteratee, while test returns true. Calls callback when stopped, or an error occurs.

Parameters:
Name Type Description
test function

synchronous truth test to perform before each execution of iteratee. Invoked with ().

iteratee AsyncFunction

An async function which is called each time test passes. Invoked with (callback).

callback function <optional>

A callback which is called after the test function has failed and repeated execution of iteratee has stopped. callback will be passed an error and any arguments passed to the final iteratee's callback. Invoked with (err, [results]);

Returns:

undefined

Example
var count = 0;
async.whilst(
    function() { return count < 5; },
    function(callback) {
        count++;
        setTimeout(function() {
            callback(null, count);
        }, 1000);
    },
    function (err, n) {
        // 5 seconds have passed, n = 5
    }
);
Source:

Type Definitions

CargoObject

import cargo from 'async/cargo';

A cargo of tasks for the worker function to complete. Cargo inherits all of the same methods and event callbacks as queue.

Type:
  • Object
Properties:
Name Type Description
length function

A function returning the number of items waiting to be processed. Invoke like cargo.length().

payload number

An integer for determining how many tasks should be process per round. This property can be changed after a cargo is created to alter the payload on-the-fly.

push function

Adds task to the queue. The callback is called once the worker has finished processing the task. Instead of a single task, an array of tasks can be submitted. The respective callback is used for every task in the list. Invoke like cargo.push(task, [callback]).

saturated function

A callback that is called when the queue.length() hits the concurrency and further tasks will be queued.

empty function

A callback that is called when the last item from the queue is given to a worker.

drain function

A callback that is called when the last item from the queue has returned from the worker.

idle function

a function returning false if there are items waiting or being processed, or true if not. Invoke like cargo.idle().

pause function

a function that pauses the processing of tasks until resume() is called. Invoke like cargo.pause().

resume function

a function that resumes the processing of queued tasks when the queue is paused. Invoke like cargo.resume().

kill function

a function that removes the drain callback and empties remaining tasks from the queue forcing it to go idle. Invoke like cargo.kill().

Source:

QueueObject

import queue from 'async/queue';

A queue of tasks for the worker function to complete.

Type:
  • Object
Properties:
Name Type Description
length function

a function returning the number of items waiting to be processed. Invoke with queue.length().

started boolean

a boolean indicating whether or not any items have been pushed and processed by the queue.

running function

a function returning the number of items currently being processed. Invoke with queue.running().

workersList function

a function returning the array of items currently being processed. Invoke with queue.workersList().

idle function

a function returning false if there are items waiting or being processed, or true if not. Invoke with queue.idle().

concurrency number

an integer for determining how many worker functions should be run in parallel. This property can be changed after a queue is created to alter the concurrency on-the-fly.

push function

add a new task to the queue. Calls callback once the worker has finished processing the task. Instead of a single task, a tasks array can be submitted. The respective callback is used for every task in the list. Invoke with queue.push(task, [callback]),

unshift function

add a new task to the front of the queue. Invoke with queue.unshift(task, [callback]).

remove function

remove items from the queue that match a test function. The test function will be passed an object with a data property, and a priority property, if this is a priorityQueue object. Invoked with queue.remove(testFn), where testFn is of the form function ({data, priority}) {} and returns a Boolean.

saturated function

a callback that is called when the number of running workers hits the concurrency limit, and further tasks will be queued.

unsaturated function

a callback that is called when the number of running workers is less than the concurrency & buffer limits, and further tasks will not be queued.

buffer number

A minimum threshold buffer in order to say that the queue is unsaturated.

empty function

a callback that is called when the last item from the queue is given to a worker.

drain function

a callback that is called when the last item from the queue has returned from the worker.

error function

a callback that is called when a task errors. Has the signature function(error, task).

paused boolean

a boolean for determining whether the queue is in a paused state.

pause function

a function that pauses the processing of tasks until resume() is called. Invoke with queue.pause().

resume function

a function that resumes the processing of queued tasks when the queue is paused. Invoke with queue.resume().

kill function

a function that removes the drain callback and empties remaining tasks from the queue forcing it to go idle. No more tasks should be pushed to the queue after calling this function. Invoke with queue.kill().

Source: