async

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with Node.js and installable via npm install --save async, it can also be used directly in the browser.

Collections

Methods

(static) concat(coll, iteratee, callbackopt)

import concat from 'async/concat';

Applies iteratee to each item in coll, concatenating the results. Returns the concatenated list. The iteratees are called in parallel, and the results are concatenated as they return. The results array will be returned in the original order of coll passed to the iteratee function.

Parameters:

A function to apply to each item in coll, which should use an array as its result. Invoked with (item, callback).

callback

function<optional>

A callback which is called after all the iteratee functions have finished, or an error occurs. Results is an array containing the concatenated results of the iteratee function. Invoked with (err, results).

Returns:

A Promise, if no callback is passed

Example

async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
// files is now a list of filenames that exist in the 3 directories
});

Parameters:

A function to apply to each item in coll, which should use an array as its result. Invoked with (item, callback).

callback

function<optional>

A callback which is called after all the iteratee functions have finished, or an error occurs. Results is an array containing the concatenated results of the iteratee function. Invoked with (err, results).

Parameters:

A function to apply to each item in coll. The iteratee should complete with an array an array of results. Invoked with (item, callback).

callback

function<optional>

A callback which is called after all the iteratee functions have finished, or an error occurs. Results is an array containing the concatenated results of the iteratee function. Invoked with (err, results).

Returns:

(static) detect(coll, iteratee, callbackopt)

import detect from 'async/detect';

Returns the first value in coll that passes an async truth test. The iteratee is applied in parallel, meaning the first iteratee to return true will fire the detect callback with that result. That means the result might not be the first item in the original coll (in terms of order) that passes the test. If order within the original coll is important, then look at detectSeries.

Parameters:

A truth test to apply to each item in coll. The iteratee must complete with a boolean value as its result. Invoked with (item, callback).

callback

function<optional>

A callback which is called as soon as any iteratee returns true, or after all the iteratee functions have finished. Result will be the first item in the array that passes the truth test (iteratee) or the value undefined if none passed. Invoked with (err, result).

Parameters:

A truth test to apply to each item in coll. The iteratee must complete with a boolean value as its result. Invoked with (item, callback).

callback

function<optional>

A callback which is called as soon as any iteratee returns true, or after all the iteratee functions have finished. Result will be the first item in the array that passes the truth test (iteratee) or the value undefined if none passed. Invoked with (err, result).

Parameters:

A truth test to apply to each item in coll. The iteratee must complete with a boolean value as its result. Invoked with (item, callback).

callback

function<optional>

A callback which is called as soon as any iteratee returns true, or after all the iteratee functions have finished. Result will be the first item in the array that passes the truth test (iteratee) or the value undefined if none passed. Invoked with (err, result).

Returns:

(static) each(coll, iteratee, callbackopt) → {Promise}

import each from 'async/each';

Applies the function iteratee to each item in coll, in parallel. The iteratee is called with an item from the list, and a callback for when it has finished. If the iteratee passes an error to its callback, the main callback (for the each function) is immediately called with the error.

Note, that since this function applies iteratee to each item in parallel, there is no guarantee that the iteratee functions will complete in order.

Returns:

(static) groupBy(coll, iteratee, callbackopt) → {Promise}

import groupBy from 'async/groupBy';

Returns a new object, where each value corresponds to an array of items, from coll, that returned the corresponding key. That is, the keys of the object correspond to the values passed to the iteratee callback.

Note: Since this function applies the iteratee to each item in parallel, there is no guarantee that the iteratee functions will complete in order. However, the values for each key in the result will be in the same order as the original coll. For Objects, the values will roughly be in the order of the original Objects' keys (but this can vary across JavaScript engines).

Returns:

(static) map(coll, iteratee, callbackopt) → {Promise}

import map from 'async/map';

Produces a new collection of values by mapping each value in coll through the iteratee function. The iteratee is called with an item from coll and a callback for when it has finished processing. Each of these callback takes 2 arguments: an error, and the transformed item from coll. If iteratee passes an error to its callback, the main callback (for the map function) is immediately called with the error.

Note, that since this function applies the iteratee to each item in parallel, there is no guarantee that the iteratee functions will complete in order. However, the results array will be in the same order as the original coll.

If map is passed an Object, the results will be an Array. The results will roughly be in the order of the original Objects' keys (but this can vary across JavaScript engines).

(static) mapValues(obj, iteratee, callbackopt) → {Promise}

Produces a new Object by mapping each value of obj through the iteratee function. The iteratee is called each value and key from obj and a callback for when it has finished processing. Each of these callbacks takes two arguments: an error, and the transformed item from obj. If iteratee passes an error to its callback, the main callback (for the mapValues function) is immediately called with the error.

Note, the order of the keys in the result is not guaranteed. The keys will be roughly in the order they complete, (but this is very engine-specific)

Parameters:

A function to apply to each value and key in coll. The iteratee should complete with the transformed value as its result. Invoked with (value, key, callback).

callback

function<optional>

A callback which is called when all iteratee functions have finished, or an error occurs. result is a new object consisting of each key from obj, with each transformed value on the right-hand side. Invoked with (err, result).

Parameters:

A function to apply to each value and key in coll. The iteratee should complete with the transformed value as its result. Invoked with (value, key, callback).

callback

function<optional>

A callback which is called when all iteratee functions have finished, or an error occurs. result is a new object consisting of each key from obj, with each transformed value on the right-hand side. Invoked with (err, result).

Parameters:

A function to apply to each value and key in coll. The iteratee should complete with the transformed value as its result. Invoked with (value, key, callback).

callback

function<optional>

A callback which is called when all iteratee functions have finished, or an error occurs. result is a new object consisting of each key from obj, with each transformed value on the right-hand side. Invoked with (err, result).

Returns:

(static) reduce(coll, memo, iteratee, callbackopt) → {Promise}

Reduces coll into a single value using an async iteratee to return each successive step. memo is the initial state of the reduction. This function only operates in series.

For performance reasons, it may make sense to split a call to this function into a parallel map, and then use the normal Array.prototype.reduce on the results. This function is for situations where each step in the reduction needs to be async; if you can get the data before reducing it, then it's probably a good idea to do so.

Alias:

foldl

Parameters:

A function applied to each item in the array to produce the next step in the reduction. The iteratee should complete with the next state of the reduction. If the iteratee complete with an error, the reduction is stopped and the main callback is immediately called with the error. Invoked with (memo, item, callback).

callback

function<optional>

A callback which is called after all the iteratee functions have finished. Result is the reduced value. Invoked with (err, result).

Parameters:

A function applied to each item in the array to produce the next step in the reduction. The iteratee should complete with the next state of the reduction. If the iteratee complete with an error, the reduction is stopped and the main callback is immediately called with the error. Invoked with (memo, item, callback).

callback

function<optional>

A callback which is called after all the iteratee functions have finished. Result is the reduced value. Invoked with (err, result).

Parameters:

An async truth test to apply to each item in the collections in parallel. The iteratee should complete with a boolean result value. Invoked with (item, callback).

callback

function<optional>

A callback which is called as soon as any iteratee returns true, or after all the iteratee functions have finished. Result will be either true or false depending on the values of the async tests. Invoked with (err, result).

Parameters:

An async truth test to apply to each item in the collections in parallel. The iteratee should complete with a boolean result value. Invoked with (item, callback).

callback

function<optional>

A callback which is called as soon as any iteratee returns true, or after all the iteratee functions have finished. Result will be either true or false depending on the values of the async tests. Invoked with (err, result).

Parameters:

An async truth test to apply to each item in the collections in series. The iteratee should complete with a boolean result value. Invoked with (item, callback).

callback

function<optional>

A callback which is called as soon as any iteratee returns true, or after all the iteratee functions have finished. Result will be either true or false depending on the values of the async tests. Invoked with (err, result).

Parameters:

An async function to apply to each item in coll. The iteratee should complete with a value to use as the sort criteria as its result. Invoked with (item, callback).

callback

function

A callback which is called after all the iteratee functions have finished, or an error occurs. Results is the items from the original coll sorted by the values returned by the iteratee calls. Invoked with (err, results).

A relative of reduce. Takes an Object or Array, and iterates over each element in parallel, each step potentially mutating an accumulator value. The type of the accumulator defaults to the type of collection passed in.

Parameters:

Name

Type

Description

coll

Array | Iterable | AsyncIterable | Object

A collection to iterate over.

accumulator

*<optional>

The initial state of the transform. If omitted, it will default to an empty Object or Array, depending on the type of coll

Methods

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. The results for each of the applied async functions are passed to the final callback as an array.

Returns:

(static) auto(tasks, concurrencyopt, callbackopt) → {Promise}

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).

(static) autoInject(tasks, callbackopt) → {Promise}

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.

Returns:

a promise, if no callback is passed

Type

Promise

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':'[email protected]'});
}
}, 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':'[email protected]'});
}]
//...
}, function(err, results) {
console.log('err = ', err);
console.log('email_link = ', results.email_link);
});

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 theseanimations 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.

Creates a cargoQueue object with the specified payload. Tasks added to the cargoQueue will be processed together (up to the payload limit) in concurrency parallel workers. If the all workers are in progress, the task is queued until one becomes available. Once a worker has completed some tasks, each callback of those tasks is called. Check out theseanimations for how cargo and queue work.

While queue passes only one task to one of a group of workers at a time, and cargo passes an array of tasks to a single worker, the cargoQueue passes an array of tasks to multiple parallel workers.

(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.

If the last argument to the composed function is not a function, a promise is returned when you call it.

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

Parameters:

asynchronous truth test to perform after each execution of iteratee. Invoked with (...args, callback), where ...args are the non-error args from the previous callback 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]);

Parameters:

asynchronous truth test to perform after each execution of iteratee. Invoked with (...args, callback), where ...args are the non-error args from the previous callback 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]);

Returns:

(static) forever(fn, errbackopt) → {Promise}

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:

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

Returns:

a promise that rejects if an error occurs and an errback is not passed

Type

Promise

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.
}
);

(static) parallel(tasks, callbackopt) → {Promise}

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 | AsyncIterable | 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).

(static) parallelLimit(tasks, limit, callbackopt) → {Promise}

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

Parameters:

Name

Type

Description

tasks

Array | Iterable | AsyncIterable | 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).

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.

(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).

(static) retry(optsopt, task, callbackopt) → {Promise}

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.

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).

Returns:

a promise if no callback provided

Type

Promise

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
});

(static) series(tasks, callbackopt) → {Promise}

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.

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 | AsyncIterable | 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).

Returns:

(static) tryEach(tasks, callbackopt) → {Promise}

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 | AsyncIterable | 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).

Parameters:

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]);

(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]).

Parameters:

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]);

Type Definitions

QueueObject

Type:

Properties:

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.

payload

number

an integer that specifies how many items are passed to the worker function at a time. only applies if this is a cargo object

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 function that sets a callback that is called when the number of running workers hits the concurrency limit, and further tasks will be queued. If the callback is omitted, q.saturated() returns a promise for the next occurrence.

unsaturated

function

a function that sets 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. If the callback is omitted, q.unsaturated() returns a promise for the next occurrence.

buffer

number

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

empty

function

a function that sets a callback that is called when the last item from the queue is given to a worker. If the callback is omitted, q.empty() returns a promise for the next occurrence.

drain

function

a function that sets a callback that is called when the last item from the queue has returned from the worker. If the callback is omitted, q.drain() returns a promise for the next occurrence.

error

function

a function that sets a callback that is called when a task errors. Has the signature function(error, task). If the callback is omitted, error() returns a promise that rejects on the next error.

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().

Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback.

If the function passed to asyncify returns a Promise, that promises's resolved/rejected state will be used to call the callback, rather than simply the synchronous return value.

This also means you can asyncify ES2017 async functions.

Alias:

wrapSync

Parameters:

Name

Type

Description

func

function

The synchronous function, or Promise-returning function to convert to an AsyncFunction.

Returns:

An asynchronous wrapper of the func. To be invoked with (args..., callback).

(static) dir(function)

import dir from 'async/dir';

Logs the result of an async function to the console using console.dir to display the properties of the resulting object. Only works in Node.js or in browsers that support console.dir and console.error (such as FF and Chrome). If multiple arguments are returned from the async function, console.dir is called on each argument in order.

Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (RangeError: Maximum call stack size exceeded) and generally keeping Zalgo contained. ES2017 async functions are returned as-is -- they are immune to Zalgo's corrupting influences, as they always resolve on a later tick.

(static) log(function)

import log from 'async/log';

Logs the result of an async function to the console. Only works in Node.js or in browsers that support console.log and console.error (such as FF and Chrome). If multiple arguments are returned from the async function, console.log is called on each argument in order.

Caches the results of an async function. When creating a hash to store function results against, the callback is omitted from the hash and an optional hash function can be used.

Note: if the async function errs, the result will not be cached and subsequent calls will call the wrapped function.

If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function.

The cache of results is exposed as the memo property of the function returned by memoize.

(static) nextTick(callback)

import nextTick from 'async/nextTick';

Calls callback on a later loop around the event loop. In Node.js this just calls process.nextTick. In the browser it will use setImmediate if available, otherwise setTimeout(callback, 0), which means other higher priority events may precede the execution of callback.

This is used internally for browser-compatibility purposes.

Parameters:

Name

Type

Description

callback

function

The function to call on a later loop around the event loop. Invoked with (args...).

args...

*

any number of additional arguments to pass to the callback on the next tick.

(static) setImmediate(callback)

import setImmediate from 'async/setImmediate';

Calls callback on a later loop around the event loop. In Node.js this just calls setImmediate. In the browser it will use setImmediate if available, otherwise setTimeout(callback, 0), which means other higher priority events may precede the execution of callback.

This is used internally for browser-compatibility purposes.

Parameters:

Name

Type

Description

callback

function

The function to call on a later loop around the event loop. Invoked with (args...).

args...

*

any number of additional arguments to pass to the callback on the next tick.

Sets a time limit on an asynchronous function. If the function does not call its callback within the specified milliseconds, it will be called with a timeout error. The code property for the error object will be 'ETIMEDOUT'.