Methods
(static) apply(fn) → {function}
import apply from 'async/apply';
Creates a continuation function with some arguments already applied.
Useful as a shorthand when combined with other control flow functions. Any arguments passed to the returned function are added to the arguments originally passed to apply.
Parameters:
Name | Type | Description |
---|---|---|
fn |
function | The function you want to eventually apply all arguments to. Invokes with (arguments...). |
arguments... |
* | Any number of arguments to automatically apply when the continuation is called. |
Returns:
the partially-applied function
- Type
- function
Example
// using apply
async.parallel([
async.apply(fs.writeFile, 'testfile1', 'test1'),
async.apply(fs.writeFile, 'testfile2', 'test2')
]);
// the same process without using apply
async.parallel([
function(callback) {
fs.writeFile('testfile1', 'test1', callback);
},
function(callback) {
fs.writeFile('testfile2', 'test2', callback);
}
]);
// It's possible to pass any number of additional arguments when calling the
// continuation:
node> var fn = async.apply(sys.puts, 'one');
node> fn('two', 'three');
one
two
three
(static) asyncify(func) → {AsyncFunction}
import asyncify from 'async/asyncify';
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)
.
- Type
- AsyncFunction
Example
// passing a regular synchronous function
async.waterfall([
async.apply(fs.readFile, filename, "utf8"),
async.asyncify(JSON.parse),
function (data, next) {
// data is the result of parsing the text.
// If there was a parsing error, it would have been caught.
}
], callback);
// passing a function returning a promise
async.waterfall([
async.apply(fs.readFile, filename, "utf8"),
async.asyncify(function (contents) {
return db.model.create(contents);
}),
function (model, next) {
// `model` is the instantiated model object.
// If there was an error, this function would be skipped.
}
], callback);
// es2017 example, though `asyncify` is not needed if your JS environment
// supports async functions out of the box
var q = async.queue(async.asyncify(async function(file) {
var intermediateStep = await processFile(file);
return await somePromise(intermediateStep)
}));
q.push(files);
- Source:
(static) constant() → {AsyncFunction}
import constant from 'async/constant';
Returns a function that when called, calls-back with the values provided.
Useful as the first function in a waterfall
, or for plugging values in to
auto
.
Parameters:
Name | Type | Description |
---|---|---|
arguments... |
* | Any number of arguments to automatically invoke callback with. |
Returns:
Returns a function that when invoked, automatically invokes the callback with the previous given arguments.
- Type
- AsyncFunction
Example
async.waterfall([
async.constant(42),
function (value, next) {
// value === 42
},
//...
], callback);
async.waterfall([
async.constant(filename, "utf8"),
fs.readFile,
function (fileData, next) {
//...
}
//...
], callback);
async.auto({
hostname: async.constant("https://server.net/"),
port: findFreePort,
launchServer: ["hostname", "port", function (options, cb) {
startServer(options, cb);
}],
//...
}, callback);
- Source:
(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.
Parameters:
Name | Type | Description |
---|---|---|
function |
AsyncFunction | The function you want to eventually apply all arguments to. |
arguments... |
* | Any number of arguments to apply to the function. |
Example
// in a module
var hello = function(name, callback) {
setTimeout(function() {
callback(null, {hello: name});
}, 1000);
};
// in the node repl
node> async.dir(hello, 'world');
{hello: 'world'}
(static) ensureAsync(fn) → {AsyncFunction}
import ensureAsync from 'async/ensureAsync';
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.
Parameters:
Name | Type | Description |
---|---|---|
fn |
AsyncFunction | an async function, one that expects a node-style callback as its last argument. |
Returns:
Returns a wrapped function with the exact same call signature as the function passed in.
- Type
- AsyncFunction
Example
function sometimesAsync(arg, callback) {
if (cache[arg]) {
return callback(null, cache[arg]); // this would be synchronous!!
} else {
doSomeIO(arg, callback); // this IO would be asynchronous
}
}
// this has a risk of stack overflows if many results are cached in a row
async.mapSeries(args, sometimesAsync, done);
// this will defer sometimesAsync's callback if necessary,
// preventing stack overflows
async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
- Source:
(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.
Parameters:
Name | Type | Description |
---|---|---|
function |
AsyncFunction | The function you want to eventually apply all arguments to. |
arguments... |
* | Any number of arguments to apply to the function. |
Example
// in a module
var hello = function(name, callback) {
setTimeout(function() {
callback(null, 'hello ' + name);
}, 1000);
};
// in the node repl
node> async.log(hello, 'world');
'hello world'
(static) memoize(fn, hasher) → {AsyncFunction}
import memoize from 'async/memoize';
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
.
Parameters:
Name | Type | Description |
---|---|---|
fn |
AsyncFunction | The async function to proxy and cache results from. |
hasher |
function | An optional function for generating a custom hash for storing results. It has all the arguments applied to it apart from the callback, and must be synchronous. |
Returns:
a memoized version of fn
- Type
- AsyncFunction
Example
var slow_fn = function(name, callback) {
// do something
callback(null, result);
};
var fn = async.memoize(slow_fn);
// fn can now be used as if it were slow_fn
fn('some name', function() {
// callback
});
- Source:
(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. |
Example
var call_order = [];
async.nextTick(function() {
call_order.push('two');
// call_order now equals ['one','two']
});
call_order.push('one');
async.setImmediate(function (a, b, c) {
// a, b, and c equal 1, 2, and 3
}, 1, 2, 3);
- Source:
- See:
(static) reflect(fn) → {function}
import reflect from 'async/reflect';
Wraps the async function in another function that always completes with a result object, even when it errors.
The result object has either the property error
or value
.
Parameters:
Name | Type | Description |
---|---|---|
fn |
AsyncFunction | The async function you want to wrap |
Returns:
- A function that always passes null to it's callback as
the error. The second argument to the callback will be an
object
with either anerror
or avalue
property.
- Type
- function
Example
async.parallel([
async.reflect(function(callback) {
// do some stuff ...
callback(null, 'one');
}),
async.reflect(function(callback) {
// do some more stuff but error ...
callback('bad stuff happened');
}),
async.reflect(function(callback) {
// do some more stuff ...
callback(null, 'two');
})
],
// optional callback
function(err, results) {
// values
// results[0].value = 'one'
// results[1].error = 'bad stuff happened'
// results[2].value = 'two'
});
- Source:
(static) reflectAll(tasks) → {Array}
import reflectAll from 'async/reflectAll';
A helper function that wraps an array or an object of functions with reflect
.
Parameters:
Name | Type | Description |
---|---|---|
tasks |
Array | Object | Iterable | The collection of
async functions to wrap in |
Returns:
Returns an array of async functions, each wrapped in
async.reflect
- Type
- Array
Example
let tasks = [
function(callback) {
setTimeout(function() {
callback(null, 'one');
}, 200);
},
function(callback) {
// do some more stuff but error ...
callback(new Error('bad stuff happened'));
},
function(callback) {
setTimeout(function() {
callback(null, 'two');
}, 100);
}
];
async.parallel(async.reflectAll(tasks),
// optional callback
function(err, results) {
// values
// results[0].value = 'one'
// results[1].error = Error('bad stuff happened')
// results[2].value = 'two'
});
// an example using an object instead of an array
let tasks = {
one: function(callback) {
setTimeout(function() {
callback(null, 'one');
}, 200);
},
two: function(callback) {
callback('two');
},
three: function(callback) {
setTimeout(function() {
callback(null, 'three');
}, 100);
}
};
async.parallel(async.reflectAll(tasks),
// optional callback
function(err, results) {
// values
// results.one.value = 'one'
// results.two.error = 'two'
// results.three.value = 'three'
});
- Source:
- See:
(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. |
Example
var call_order = [];
async.nextTick(function() {
call_order.push('two');
// call_order now equals ['one','two']
});
call_order.push('one');
async.setImmediate(function (a, b, c) {
// a, b, and c equal 1, 2, and 3
}, 1, 2, 3);
- Source:
- See:
(static) timeout(asyncFn, milliseconds, infoopt) → {AsyncFunction}
import timeout from 'async/timeout';
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'
.
Parameters:
Name | Type | Description |
---|---|---|
asyncFn |
AsyncFunction | The async function to limit in time. |
milliseconds |
number | The specified time limit. |
info |
* <optional> | Any variable you want attached ( |
Returns:
Returns a wrapped function that can be used with any
of the control flow functions.
Invoke this function with the same parameters as you would asyncFunc
.
- Type
- AsyncFunction
Example
function myFunction(foo, callback) {
doAsyncTask(foo, function(err, data) {
// handle errors
if (err) return callback(err);
// do some stuff ...
// return processed data
return callback(null, data);
});
}
var wrapped = async.timeout(myFunction, 1000);
// call `wrapped` as you would `myFunction`
wrapped({ bar: 'bar' }, function(err, data) {
// if `myFunction` takes < 1000 ms to execute, `err`
// and `data` will have their expected values
// else `err` will be an Error with the code 'ETIMEDOUT'
});
- Source:
(static) unmemoize(fn) → {AsyncFunction}
import unmemoize from 'async/unmemoize';
Undoes a memoized function, reverting it to the original, unmemoized form. Handy for testing.
Parameters:
Name | Type | Description |
---|---|---|
fn |
AsyncFunction | the memoized function |
Returns:
a function that calls the original unmemoized function
- Type
- AsyncFunction
- Source:
- See: