A collection of async
functions for controlling the flow through a script.
Methods
(static) applyEach(fns, …argsopt, callbackopt) → {AsyncFunction}
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. The results
for each of the applied async functions are passed to the final callback
as an array.
Parameters:
Name | Type | Description |
---|---|---|
fns |
Array | Iterable | AsyncIterable | 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:
- Returns a function that takes no args other than
an optional callback, that is the result of applying the
args
to each of the functions.
- Type
- AsyncFunction
Example
const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')
appliedFn((err, results) => {
// results[0] is the results for `enableSearch`
// results[1] is the results for `updateSchema`
});
// partial application example:
async.each(
buckets,
async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),
callback
);
- Source:
(static) applyEachSeries(fns, …argsopt, callbackopt) → {AsyncFunction}
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 | AsyncIterable | 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:
- A function, that when called, is the result of
appling the
args
to the list of functions. It takes no args, other than a callback.
- Type
- AsyncFunction
- Source:
- See:
(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:
|
|
concurrency |
number <optional> | Infinity | An optional |
callback |
function <optional> | An optional callback which is called when all
the tasks have been completed. It receives the |
Returns:
a promise, if a callback is not passed
- Type
- Promise
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);
});
(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.
|
callback |
function <optional> | An optional callback which is called when all
the tasks have been completed. It receives the |
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':'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) → {QueueObject}
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 |
|
payload |
number <optional> | Infinity | An optional |
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
- QueueObject
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');
});
await cargo.push({name: 'baz'});
console.log('finished processing baz');
- Source:
- See:
(static) cargoQueue(worker, concurrencyopt, payloadopt) → {QueueObject}
import cargoQueue from 'async/cargoQueue';
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 these animations
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.
Parameters:
Name | Type | Default | Description |
---|---|---|---|
worker |
AsyncFunction | An asynchronous function for processing an array
of queued tasks. Invoked with |
|
concurrency |
number <optional> | 1 | An |
payload |
number <optional> | Infinity | An optional |
Returns:
A cargoQueue object to manage the tasks. Callbacks can attached as certain properties to listen for specific events during the lifecycle of the cargoQueue and inner queue.
- Type
- QueueObject
Example
// create a cargoQueue object with payload 2 and concurrency 2
var cargoQueue = async.cargoQueue(function(tasks, callback) {
for (var i=0; i<tasks.length; i++) {
console.log('hello ' + tasks[i].name);
}
callback();
}, 2, 2);
// add some items
cargoQueue.push({name: 'foo'}, function(err) {
console.log('finished processing foo');
});
cargoQueue.push({name: 'bar'}, function(err) {
console.log('finished processing bar');
});
cargoQueue.push({name: 'baz'}, function(err) {
console.log('finished processing baz');
});
cargoQueue.push({name: 'boo'}, function(err) {
console.log('finished processing boo');
});
- Source:
- See:
-
async.cargo
(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:
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) doUntil(iteratee, test, callbackopt) → {Promise}
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 |
AsyncFunction | asynchronous truth test to perform after each
execution of |
callback |
function <optional> | A callback which is called after the test
function has passed and repeated execution of |
Returns:
a promise, if no callback is passed
- Type
- Promise
- Source:
- See:
(static) doWhilst(iteratee, test, callbackopt) → {Promise}
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 |
AsyncFunction | asynchronous truth test to perform after each
execution of |
callback |
function <optional> | A callback which is called after the test
function has failed and repeated execution of |
Returns:
a promise, if no callback is passed
- Type
- Promise
- Source:
- See:
(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:
Name | Type | Description |
---|---|---|
fn |
AsyncFunction | an async function to call repeatedly. Invoked with (next). |
errback |
function <optional> | when |
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.
}
);
- Source:
(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 |
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). |
Returns:
a promise, if a callback is not passed
- Type
- Promise
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) → {Promise}
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 | AsyncIterable | Object | A collection of
async functions to run.
Each async function can complete with any number of optional |
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). |
Returns:
a promise, if a callback is not passed
- Type
- Promise
- 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
|
concurrency |
number | An |
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 oftasks
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
worker
s 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
|
|
concurrency |
number <optional> | 1 | An |
Returns:
A queue object to manage the tasks. Callbacks can be 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');
});
// or await the end
await q.drain()
// assign an error callback
q.error(function(err, task) {
console.error('task experienced an error');
});
// add some items to the queue
q.push({name: 'foo'}, function(err) {
console.log('finished processing foo');
});
// callback is optional
q.push({name: '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');
});
(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 |
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
});
(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
|
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 |
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
});
- 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 |
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) → {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.
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 | AsyncIterable | Object | A collection containing
async functions to run in series.
Each function can complete with any number of optional |
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 |
Returns:
a promise, if no callback is passed
- Type
- Promise
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}
});
(static) times(n, iteratee, callback) → {Promise}
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 |
callback |
function | see map. |
Returns:
a promise, if no callback is provided
- Type
- Promise
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
});
(static) timesLimit(count, limit, iteratee, callback) → {Promise}
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 |
callback |
function | see async.map. |
Returns:
a promise, if no callback is provided
- Type
- Promise
- Source:
- See:
(static) timesSeries(n, iteratee, callback) → {Promise}
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 |
callback |
function | see map. |
Returns:
a promise, if no callback is provided
- Type
- Promise
- Source:
- See:
(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 |
function <optional> | An optional callback which is called when one
of the tasks has succeeded, or all have failed. It receives the |
Returns:
a promise, if no callback is passed
- Type
- Promise
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) → {Promise}
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 |
AsyncFunction | asynchronous truth test to perform before each
execution of |
iteratee |
AsyncFunction | An async function which is called each time
|
callback |
function <optional> | A callback which is called after the test
function has passed and repeated execution of |
Returns:
a promise, if a callback is not passed
- Type
- Promise
Example
const results = []
let finished = false
async.until(function test(page, cb) {
cb(null, finished)
}, function iter(next) {
fetchPage(url, (err, body) => {
if (err) return next(err)
results = results.concat(body.objects)
finished = !!body.next
next(err)
})
}, function done (err) {
// all pages have been fetched
})
- 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 |
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) → {Promise}
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 |
AsyncFunction | asynchronous truth test to perform before each
execution of |
iteratee |
AsyncFunction | An async function which is called each time
|
callback |
function <optional> | A callback which is called after the test
function has failed and repeated execution of |
Returns:
a promise, if no callback is passed
- Type
- Promise
Example
var count = 0;
async.whilst(
function test(cb) { cb(null, count < 5); },
function iter(callback) {
count++;
setTimeout(function() {
callback(null, count);
}, 1000);
},
function (err, n) {
// 5 seconds have passed, n = 5
}
);
Type Definitions
QueueObject
import queue from 'async/queue';
A queue of tasks for the worker function to complete.
Type:
- Iterable
Properties:
Name | Type | Description |
---|---|---|
length |
function | a function returning the number of items
waiting to be processed. Invoke with |
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 |
workersList |
function | a function returning the array of items
currently being processed. Invoke with |
idle |
function | a function returning false if there are items
waiting or being processed, or true if not. Invoke with |
concurrency |
number | an integer for determining how many |
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 |
AsyncFunction | add a new task to the |
unshift |
AsyncFunction | add a new task to the front of the |
pushAsync |
AsyncFunction | the same as |
unshiftAsync |
AsyncFunction | the same as |
remove |
function | remove items from the queue that match a test
function. The test function will be passed an object with a |
saturated |
function | a function that sets a callback that is
called when the number of running workers hits the |
unsaturated |
function | a function that sets a callback that is
called when the number of running workers is less than the |
buffer |
number | A minimum threshold buffer in order to say that
the |
empty |
function | a function that sets a callback that is called
when the last item from the |
drain |
function | a function that sets a callback that is called
when the last item from the |
error |
function | a function that sets a callback that is called
when a task errors. Has the signature |
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 |
function | a function that resumes the processing of
queued tasks when the queue is paused. Invoke with |
kill |
function | a function that removes the |
Example
const q = async.queue(worker, 2)
q.push(item1)
q.push(item2)
q.push(item3)
// queues are iterable, spread into an array to inspect
const items = [...q] // [item1, item2, item3]
// or use for of
for (let item of q) {
console.log(item)
}
q.drain(() => {
console.log('all done')
})
// or
await q.drain()