A collection of async
functions for manipulating collections, such as
arrays and objects.
- Source:
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 iteratee
s 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.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
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
// dir1 is a directory that contains file1.txt, file2.txt
// dir2 is a directory that contains file3.txt, file4.txt
// dir3 is a directory that contains file5.txt
// dir4 does not exist
let directoryList = ['dir1','dir2','dir3'];
let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];
// Using callbacks
async.concat(directoryList, fs.readdir, function(err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
// [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
}
});
// Error Handling
async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {
if (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
// since dir4 does not exist
} else {
console.log(results);
}
});
// Using Promises
async.concat(directoryList, fs.readdir)
.then(results => {
console.log(results);
// [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
}).catch(err => {
console.log(err);
});
// Error Handling
async.concat(withMissingDirectoryList, fs.readdir)
.then(results => {
console.log(results);
}).catch(err => {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
// since dir4 does not exist
});
// Using async/await
async () => {
try {
let results = await async.concat(directoryList, fs.readdir);
console.log(results);
// [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
} catch (err) {
console.log(err);
}
}
// Error Handling
async () => {
try {
let results = await async.concat(withMissingDirectoryList, fs.readdir);
console.log(results);
} catch (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
// since dir4 does not exist
}
}
- Source:
(static) concatLimit(coll, limit, iteratee, callbackopt)
import concatLimit from 'async/concatLimit';
The same as concat
but runs a maximum of limit
async operations at a time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
AsyncFunction
|
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
- Source:
- See:
-
(static) concatSeries(coll, iteratee, callbackopt)
import concatSeries from 'async/concatSeries';
The same as concat
but runs only a single async operation at a time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
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:
A Promise, if no callback is passed
- Source:
- See:
-
(static) detect(coll, iteratee, callbackopt) → {Promise}
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
.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
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:
a promise, if a callback is omitted
-
Type
-
Promise
Example
// dir1 is a directory that contains file1.txt, file2.txt
// dir2 is a directory that contains file3.txt, file4.txt
// dir3 is a directory that contains file5.txt
// asynchronous function that checks if a file exists
function fileExists(file, callback) {
fs.access(file, fs.constants.F_OK, (err) => {
callback(null, !err);
});
}
async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,
function(err, result) {
console.log(result);
// dir1/file1.txt
// result now equals the first file in the list that exists
}
);
// Using Promises
async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)
.then(result => {
console.log(result);
// dir1/file1.txt
// result now equals the first file in the list that exists
}).catch(err => {
console.log(err);
});
// Using async/await
async () => {
try {
let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists);
console.log(result);
// dir1/file1.txt
// result now equals the file in the list that exists
}
catch (err) {
console.log(err);
}
}
- Source:
(static) detectLimit(coll, limit, iteratee, callbackopt) → {Promise}
import detectLimit from 'async/detectLimit';
The same as detect
but runs a maximum of limit
async operations at a
time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
AsyncFunction
|
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:
a promise, if a callback is omitted
-
Type
-
Promise
- Source:
- See:
-
(static) detectSeries(coll, iteratee, callbackopt) → {Promise}
import detectSeries from 'async/detectSeries';
The same as detect
but runs only a single async operation at a time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
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:
a promise, if a callback is omitted
-
Type
-
Promise
- Source:
- See:
-
(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.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
An async function to apply to
each item in coll . Invoked with (item, callback).
The array index is not passed to the iteratee.
If you need the index, use eachOf . |
callback |
function
<optional>
|
A callback which is called when all
iteratee functions have finished, or an error occurs. Invoked with (err). |
Returns:
a promise, if a callback is omitted
-
Type
-
Promise
Example
// dir1 is a directory that contains file1.txt, file2.txt
// dir2 is a directory that contains file3.txt, file4.txt
// dir3 is a directory that contains file5.txt
// dir4 does not exist
const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];
const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];
// asynchronous function that deletes a file
const deleteFile = function(file, callback) {
fs.unlink(file, callback);
};
// Using callbacks
async.each(fileList, deleteFile, function(err) {
if( err ) {
console.log(err);
} else {
console.log('All files have been deleted successfully');
}
});
// Error Handling
async.each(withMissingFileList, deleteFile, function(err){
console.log(err);
// [ Error: ENOENT: no such file or directory ]
// since dir4/file2.txt does not exist
// dir1/file1.txt could have been deleted
});
// Using Promises
async.each(fileList, deleteFile)
.then( () => {
console.log('All files have been deleted successfully');
}).catch( err => {
console.log(err);
});
// Error Handling
async.each(fileList, deleteFile)
.then( () => {
console.log('All files have been deleted successfully');
}).catch( err => {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
// since dir4/file2.txt does not exist
// dir1/file1.txt could have been deleted
});
// Using async/await
async () => {
try {
await async.each(files, deleteFile);
}
catch (err) {
console.log(err);
}
}
// Error Handling
async () => {
try {
await async.each(withMissingFileList, deleteFile);
}
catch (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
// since dir4/file2.txt does not exist
// dir1/file1.txt could have been deleted
}
}
- Source:
(static) eachLimit(coll, limit, iteratee, callbackopt) → {Promise}
import eachLimit from 'async/eachLimit';
The same as each
but runs a maximum of limit
async operations at a time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
AsyncFunction
|
An async function to apply to each item in
coll .
The array index is not passed to the iteratee.
If you need the index, use eachOfLimit .
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called when all
iteratee functions have finished, or an error occurs. Invoked with (err). |
Returns:
a promise, if a callback is omitted
-
Type
-
Promise
- Source:
- See:
-
(static) eachOf(coll, iteratee, callbackopt) → {Promise}
import eachOf from 'async/eachOf';
Like each
, except that it passes the key (or index) as the second argument
to the iteratee.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
A function to apply to each
item in coll .
The key is the item's key, or index in the case of an array.
Invoked with (item, key, callback). |
callback |
function
<optional>
|
A callback which is called when all
iteratee functions have finished, or an error occurs. Invoked with (err). |
Returns:
a promise, if a callback is omitted
-
Type
-
Promise
Example
// dev.json is a file containing a valid json object config for dev environment
// dev.json is a file containing a valid json object config for test environment
// prod.json is a file containing a valid json object config for prod environment
// invalid.json is a file with a malformed json object
let configs = {}; //global variable
let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};
let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};
// asynchronous function that reads a json file and parses the contents as json object
function parseFile(file, key, callback) {
fs.readFile(file, "utf8", function(err, data) {
if (err) return calback(err);
try {
configs[key] = JSON.parse(data);
} catch (e) {
return callback(e);
}
callback();
});
}
// Using callbacks
async.forEachOf(validConfigFileMap, parseFile, function (err) {
if (err) {
console.error(err);
} else {
console.log(configs);
// configs is now a map of JSON data, e.g.
// { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
}
});
//Error handing
async.forEachOf(invalidConfigFileMap, parseFile, function (err) {
if (err) {
console.error(err);
// JSON parse error exception
} else {
console.log(configs);
}
});
// Using Promises
async.forEachOf(validConfigFileMap, parseFile)
.then( () => {
console.log(configs);
// configs is now a map of JSON data, e.g.
// { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
}).catch( err => {
console.error(err);
});
//Error handing
async.forEachOf(invalidConfigFileMap, parseFile)
.then( () => {
console.log(configs);
}).catch( err => {
console.error(err);
// JSON parse error exception
});
// Using async/await
async () => {
try {
let result = await async.forEachOf(validConfigFileMap, parseFile);
console.log(configs);
// configs is now a map of JSON data, e.g.
// { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
}
catch (err) {
console.log(err);
}
}
//Error handing
async () => {
try {
let result = await async.forEachOf(invalidConfigFileMap, parseFile);
console.log(configs);
}
catch (err) {
console.log(err);
// JSON parse error exception
}
}
- Source:
- See:
-
(static) eachOfLimit(coll, limit, iteratee, callbackopt) → {Promise}
import eachOfLimit from 'async/eachOfLimit';
The same as eachOf
but runs a maximum of limit
async operations at a
time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
AsyncFunction
|
An async function to apply to each
item in coll . The key is the item's key, or index in the case of an
array.
Invoked with (item, key, callback). |
callback |
function
<optional>
|
A callback which is called when all
iteratee functions have finished, or an error occurs. Invoked with (err). |
Returns:
a promise, if a callback is omitted
-
Type
-
Promise
- Source:
- See:
-
(static) eachOfSeries(coll, iteratee, callbackopt) → {Promise}
import eachOfSeries from 'async/eachOfSeries';
The same as eachOf
but runs only a single async operation at a time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
An async function to apply to each item in
coll .
Invoked with (item, key, callback). |
callback |
function
<optional>
|
A callback which is called when all iteratee
functions have finished, or an error occurs. Invoked with (err). |
Returns:
a promise, if a callback is omitted
-
Type
-
Promise
- Source:
- See:
-
(static) eachSeries(coll, iteratee, callbackopt) → {Promise}
import eachSeries from 'async/eachSeries';
The same as each
but runs only a single async operation at a time.
Note, that unlike each
, this function applies iteratee to each item
in series and therefore the iteratee functions will complete in order.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
An async function to apply to each
item in coll .
The array index is not passed to the iteratee.
If you need the index, use eachOfSeries .
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called when all
iteratee functions have finished, or an error occurs. Invoked with (err). |
Returns:
a promise, if a callback is omitted
-
Type
-
Promise
- Source:
- See:
-
(static) every(coll, iteratee, callbackopt) → {Promise}
import every from 'async/every';
Returns true
if every element in coll
satisfies an async test. If any
iteratee call returns false
, the main callback
is immediately called.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
An async truth test to apply to each item
in the collection in parallel.
The iteratee must complete with a boolean result value.
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called 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). |
Returns:
a promise, if no callback provided
-
Type
-
Promise
Example
// dir1 is a directory that contains file1.txt, file2.txt
// dir2 is a directory that contains file3.txt, file4.txt
// dir3 is a directory that contains file5.txt
// dir4 does not exist
const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];
const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
// asynchronous function that checks if a file exists
function fileExists(file, callback) {
fs.access(file, fs.constants.F_OK, (err) => {
callback(null, !err);
});
}
// Using callbacks
async.every(fileList, fileExists, function(err, result) {
console.log(result);
// true
// result is true since every file exists
});
async.every(withMissingFileList, fileExists, function(err, result) {
console.log(result);
// false
// result is false since NOT every file exists
});
// Using Promises
async.every(fileList, fileExists)
.then( result => {
console.log(result);
// true
// result is true since every file exists
}).catch( err => {
console.log(err);
});
async.every(withMissingFileList, fileExists)
.then( result => {
console.log(result);
// false
// result is false since NOT every file exists
}).catch( err => {
console.log(err);
});
// Using async/await
async () => {
try {
let result = await async.every(fileList, fileExists);
console.log(result);
// true
// result is true since every file exists
}
catch (err) {
console.log(err);
}
}
async () => {
try {
let result = await async.every(withMissingFileList, fileExists);
console.log(result);
// false
// result is false since NOT every file exists
}
catch (err) {
console.log(err);
}
}
- Source:
(static) everyLimit(coll, limit, iteratee, callbackopt) → {Promise}
import everyLimit from 'async/everyLimit';
The same as every
but runs a maximum of limit
async operations at a time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
AsyncFunction
|
An async truth test to apply to each item
in the collection in parallel.
The iteratee must complete with a boolean result value.
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called 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). |
Returns:
a promise, if no callback provided
-
Type
-
Promise
- Source:
- See:
-
(static) everySeries(coll, iteratee, callbackopt) → {Promise}
import everySeries from 'async/everySeries';
The same as every
but runs only a single async operation at a time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
An async truth test to apply to each item
in the collection in series.
The iteratee must complete with a boolean result value.
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called 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). |
Returns:
a promise, if no callback provided
-
Type
-
Promise
- Source:
- See:
-
(static) filter(coll, iteratee, callbackopt) → {Promise}
import filter from 'async/filter';
Returns a new array of all the values in coll
which pass an async truth
test. This operation is performed in parallel, but the results array will be
in the same order as the original.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
function
|
A truth test to apply to each item in coll .
The iteratee is passed a callback(err, truthValue) , which must be called
with a boolean argument once it has completed. Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called after all the
iteratee functions have finished. Invoked with (err, results). |
Returns:
a promise, if no callback provided
-
Type
-
Promise
Example
// dir1 is a directory that contains file1.txt, file2.txt
// dir2 is a directory that contains file3.txt, file4.txt
// dir3 is a directory that contains file5.txt
const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
// asynchronous function that checks if a file exists
function fileExists(file, callback) {
fs.access(file, fs.constants.F_OK, (err) => {
callback(null, !err);
});
}
// Using callbacks
async.filter(files, fileExists, function(err, results) {
if(err) {
console.log(err);
} else {
console.log(results);
// [ 'dir1/file1.txt', 'dir2/file3.txt' ]
// results is now an array of the existing files
}
});
// Using Promises
async.filter(files, fileExists)
.then(results => {
console.log(results);
// [ 'dir1/file1.txt', 'dir2/file3.txt' ]
// results is now an array of the existing files
}).catch(err => {
console.log(err);
});
// Using async/await
async () => {
try {
let results = await async.filter(files, fileExists);
console.log(results);
// [ 'dir1/file1.txt', 'dir2/file3.txt' ]
// results is now an array of the existing files
}
catch (err) {
console.log(err);
}
}
- Source:
(static) filterLimit(coll, limit, iteratee, callbackopt) → {Promise}
import filterLimit from 'async/filterLimit';
The same as filter
but runs a maximum of limit
async operations at a
time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
function
|
A truth test to apply to each item in coll .
The iteratee is passed a callback(err, truthValue) , which must be called
with a boolean argument once it has completed. Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called after all the
iteratee functions have finished. Invoked with (err, results). |
Returns:
a promise, if no callback provided
-
Type
-
Promise
- Source:
- See:
-
(static) filterSeries(coll, iteratee, callbackopt) → {Promise}
import filterSeries from 'async/filterSeries';
The same as filter
but runs only a single async operation at a time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
function
|
A truth test to apply to each item in coll .
The iteratee is passed a callback(err, truthValue) , which must be called
with a boolean argument once it has completed. Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called after all the
iteratee functions have finished. Invoked with (err, results) |
Returns:
a promise, if no callback provided
-
Type
-
Promise
- Source:
- See:
-
(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).
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
An async function to apply to each item in
coll .
The iteratee should complete with a key to group the value under.
Invoked with (value, callback). |
callback |
function
<optional>
|
A callback which is called when all iteratee
functions have finished, or an error occurs. Result is an Object whoses
properties are arrays of values which returned the corresponding key. |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
Example
// dir1 is a directory that contains file1.txt, file2.txt
// dir2 is a directory that contains file3.txt, file4.txt
// dir3 is a directory that contains file5.txt
// dir4 does not exist
const files = ['dir1/file1.txt','dir2','dir4']
// asynchronous function that detects file type as none, file, or directory
function detectFile(file, callback) {
fs.stat(file, function(err, stat) {
if (err) {
return callback(null, 'none');
}
callback(null, stat.isDirectory() ? 'directory' : 'file');
});
}
//Using callbacks
async.groupBy(files, detectFile, function(err, result) {
if(err) {
console.log(err);
} else {
console.log(result);
// {
// file: [ 'dir1/file1.txt' ],
// none: [ 'dir4' ],
// directory: [ 'dir2']
// }
// result is object containing the files grouped by type
}
});
// Using Promises
async.groupBy(files, detectFile)
.then( result => {
console.log(result);
// {
// file: [ 'dir1/file1.txt' ],
// none: [ 'dir4' ],
// directory: [ 'dir2']
// }
// result is object containing the files grouped by type
}).catch( err => {
console.log(err);
});
// Using async/await
async () => {
try {
let result = await async.groupBy(files, detectFile);
console.log(result);
// {
// file: [ 'dir1/file1.txt' ],
// none: [ 'dir4' ],
// directory: [ 'dir2']
// }
// result is object containing the files grouped by type
}
catch (err) {
console.log(err);
}
}
- Source:
(static) groupByLimit(coll, limit, iteratee, callbackopt) → {Promise}
import groupByLimit from 'async/groupByLimit';
The same as groupBy
but runs a maximum of limit
async operations at a time.
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
AsyncFunction
|
An async function to apply to each item in
coll .
The iteratee should complete with a key to group the value under.
Invoked with (value, callback). |
callback |
function
<optional>
|
A callback which is called when all iteratee
functions have finished, or an error occurs. Result is an Object whoses
properties are arrays of values which returned the corresponding key. |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
- Source:
- See:
-
(static) groupBySeries(coll, iteratee, callbackopt) → {Promise}
import groupBySeries from 'async/groupBySeries';
The same as groupBy
but runs only a single async operation at a time.
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
An async function to apply to each item in
coll .
The iteratee should complete with a key to group the value under.
Invoked with (value, callback). |
callback |
function
<optional>
|
A callback which is called when all iteratee
functions have finished, or an error occurs. Result is an Object whose
properties are arrays of values which returned the corresponding key. |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
- Source:
- See:
-
(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 callbacks
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).
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
An async function to apply to each item in
coll .
The iteratee should complete with the transformed item.
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called when all iteratee
functions have finished, or an error occurs. Results is an Array of the
transformed items from the coll . Invoked with (err, results). |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
Example
// file1.txt is a file that is 1000 bytes in size
// file2.txt is a file that is 2000 bytes in size
// file3.txt is a file that is 3000 bytes in size
// file4.txt does not exist
const fileList = ['file1.txt','file2.txt','file3.txt'];
const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
// asynchronous function that returns the file size in bytes
function getFileSizeInBytes(file, callback) {
fs.stat(file, function(err, stat) {
if (err) {
return callback(err);
}
callback(null, stat.size);
});
}
// Using callbacks
async.map(fileList, getFileSizeInBytes, function(err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
// results is now an array of the file size in bytes for each file, e.g.
// [ 1000, 2000, 3000]
}
});
// Error Handling
async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {
if (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
} else {
console.log(results);
}
});
// Using Promises
async.map(fileList, getFileSizeInBytes)
.then( results => {
console.log(results);
// results is now an array of the file size in bytes for each file, e.g.
// [ 1000, 2000, 3000]
}).catch( err => {
console.log(err);
});
// Error Handling
async.map(withMissingFileList, getFileSizeInBytes)
.then( results => {
console.log(results);
}).catch( err => {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
});
// Using async/await
async () => {
try {
let results = await async.map(fileList, getFileSizeInBytes);
console.log(results);
// results is now an array of the file size in bytes for each file, e.g.
// [ 1000, 2000, 3000]
}
catch (err) {
console.log(err);
}
}
// Error Handling
async () => {
try {
let results = await async.map(withMissingFileList, getFileSizeInBytes);
console.log(results);
}
catch (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
}
}
- Source:
(static) mapLimit(coll, limit, iteratee, callbackopt) → {Promise}
import mapLimit from 'async/mapLimit';
The same as map
but runs a maximum of limit
async operations at a time.
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
AsyncFunction
|
An async function to apply to each item in
coll .
The iteratee should complete with the transformed item.
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called when all iteratee
functions have finished, or an error occurs. Results is an array of the
transformed items from the coll . Invoked with (err, results). |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
- Source:
- See:
-
(static) mapSeries(coll, iteratee, callbackopt) → {Promise}
import mapSeries from 'async/mapSeries';
The same as map
but runs only a single async operation at a time.
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
An async function to apply to each item in
coll .
The iteratee should complete with the transformed item.
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called when all iteratee
functions have finished, or an error occurs. Results is an array of the
transformed items from the coll . Invoked with (err, results). |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
- Source:
- See:
-
(static) mapValues(obj, iteratee, callbackopt) → {Promise}
import mapValues from 'async/mapValues';
A relative of map
, designed for use with objects.
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:
Name |
Type |
Description |
obj |
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
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:
a promise, if no callback is passed
-
Type
-
Promise
Example
// file1.txt is a file that is 1000 bytes in size
// file2.txt is a file that is 2000 bytes in size
// file3.txt is a file that is 3000 bytes in size
// file4.txt does not exist
const fileMap = {
f1: 'file1.txt',
f2: 'file2.txt',
f3: 'file3.txt'
};
const withMissingFileMap = {
f1: 'file1.txt',
f2: 'file2.txt',
f3: 'file4.txt'
};
// asynchronous function that returns the file size in bytes
function getFileSizeInBytes(file, key, callback) {
fs.stat(file, function(err, stat) {
if (err) {
return callback(err);
}
callback(null, stat.size);
});
}
// Using callbacks
async.mapValues(fileMap, getFileSizeInBytes, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
// result is now a map of file size in bytes for each file, e.g.
// {
// f1: 1000,
// f2: 2000,
// f3: 3000
// }
}
});
// Error handling
async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) {
if (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
} else {
console.log(result);
}
});
// Using Promises
async.mapValues(fileMap, getFileSizeInBytes)
.then( result => {
console.log(result);
// result is now a map of file size in bytes for each file, e.g.
// {
// f1: 1000,
// f2: 2000,
// f3: 3000
// }
}).catch (err => {
console.log(err);
});
// Error Handling
async.mapValues(withMissingFileMap, getFileSizeInBytes)
.then( result => {
console.log(result);
}).catch (err => {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
});
// Using async/await
async () => {
try {
let result = await async.mapValues(fileMap, getFileSizeInBytes);
console.log(result);
// result is now a map of file size in bytes for each file, e.g.
// {
// f1: 1000,
// f2: 2000,
// f3: 3000
// }
}
catch (err) {
console.log(err);
}
}
// Error Handling
async () => {
try {
let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes);
console.log(result);
}
catch (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
}
}
- Source:
(static) mapValuesLimit(obj, limit, iteratee, callbackopt) → {Promise}
import mapValuesLimit from 'async/mapValuesLimit';
The same as mapValues
but runs a maximum of limit
async operations at a
time.
Parameters:
Name |
Type |
Description |
obj |
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
AsyncFunction
|
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:
a promise, if no callback is passed
-
Type
-
Promise
- Source:
- See:
-
(static) mapValuesSeries(obj, iteratee, callbackopt) → {Promise}
import mapValuesSeries from 'async/mapValuesSeries';
The same as mapValues
but runs only a single async operation at a time.
Parameters:
Name |
Type |
Description |
obj |
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
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:
a promise, if no callback is passed
-
Type
-
Promise
- Source:
- See:
-
(static) reduce(coll, memo, iteratee, callbackopt) → {Promise}
import reduce from 'async/reduce';
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:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
memo |
*
|
The initial state of the reduction. |
iteratee |
AsyncFunction
|
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 completes 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). |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
Example
// file1.txt is a file that is 1000 bytes in size
// file2.txt is a file that is 2000 bytes in size
// file3.txt is a file that is 3000 bytes in size
// file4.txt does not exist
const fileList = ['file1.txt','file2.txt','file3.txt'];
const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];
// asynchronous function that computes the file size in bytes
// file size is added to the memoized value, then returned
function getFileSizeInBytes(memo, file, callback) {
fs.stat(file, function(err, stat) {
if (err) {
return callback(err);
}
callback(null, memo + stat.size);
});
}
// Using callbacks
async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
// 6000
// which is the sum of the file sizes of the three files
}
});
// Error Handling
async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) {
if (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
} else {
console.log(result);
}
});
// Using Promises
async.reduce(fileList, 0, getFileSizeInBytes)
.then( result => {
console.log(result);
// 6000
// which is the sum of the file sizes of the three files
}).catch( err => {
console.log(err);
});
// Error Handling
async.reduce(withMissingFileList, 0, getFileSizeInBytes)
.then( result => {
console.log(result);
}).catch( err => {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
});
// Using async/await
async () => {
try {
let result = await async.reduce(fileList, 0, getFileSizeInBytes);
console.log(result);
// 6000
// which is the sum of the file sizes of the three files
}
catch (err) {
console.log(err);
}
}
// Error Handling
async () => {
try {
let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);
console.log(result);
}
catch (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
}
}
- Source:
(static) reduceRight(array, memo, iteratee, callbackopt) → {Promise}
import reduceRight from 'async/reduceRight';
Same as reduce
, only operates on array
in reverse order.
- Alias:
Parameters:
Name |
Type |
Description |
array |
Array
|
A collection to iterate over. |
memo |
*
|
The initial state of the reduction. |
iteratee |
AsyncFunction
|
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 completes 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). |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
- Source:
- See:
-
(static) reject(coll, iteratee, callbackopt) → {Promise}
import reject from 'async/reject';
The opposite of filter
. Removes values that pass an async
truth test.
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
function
|
An async truth test to apply to each item in
coll .
The should complete with a boolean value as its result .
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called after all the
iteratee functions have finished. Invoked with (err, results). |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
Example
// dir1 is a directory that contains file1.txt, file2.txt
// dir2 is a directory that contains file3.txt, file4.txt
// dir3 is a directory that contains file5.txt
const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
// asynchronous function that checks if a file exists
function fileExists(file, callback) {
fs.access(file, fs.constants.F_OK, (err) => {
callback(null, !err);
});
}
// Using callbacks
async.reject(fileList, fileExists, function(err, results) {
// [ 'dir3/file6.txt' ]
// results now equals an array of the non-existing files
});
// Using Promises
async.reject(fileList, fileExists)
.then( results => {
console.log(results);
// [ 'dir3/file6.txt' ]
// results now equals an array of the non-existing files
}).catch( err => {
console.log(err);
});
// Using async/await
async () => {
try {
let results = await async.reject(fileList, fileExists);
console.log(results);
// [ 'dir3/file6.txt' ]
// results now equals an array of the non-existing files
}
catch (err) {
console.log(err);
}
}
- Source:
- See:
-
(static) rejectLimit(coll, limit, iteratee, callbackopt) → {Promise}
import rejectLimit from 'async/rejectLimit';
The same as reject
but runs a maximum of limit
async operations at a
time.
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
function
|
An async truth test to apply to each item in
coll .
The should complete with a boolean value as its result .
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called after all the
iteratee functions have finished. Invoked with (err, results). |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
- Source:
- See:
-
(static) rejectSeries(coll, iteratee, callbackopt) → {Promise}
import rejectSeries from 'async/rejectSeries';
The same as reject
but runs only a single async operation at a time.
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
function
|
An async truth test to apply to each item in
coll .
The should complete with a boolean value as its result .
Invoked with (item, callback). |
callback |
function
<optional>
|
A callback which is called after all the
iteratee functions have finished. Invoked with (err, results). |
Returns:
a promise, if no callback is passed
-
Type
-
Promise
- Source:
- See:
-
(static) some(coll, iteratee, callbackopt) → {Promise}
import some from 'async/some';
Returns true
if at least one element in the coll
satisfies an async test.
If any iteratee call returns true
, the main callback
is immediately
called.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
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). |
Returns:
a promise, if no callback provided
-
Type
-
Promise
Example
// dir1 is a directory that contains file1.txt, file2.txt
// dir2 is a directory that contains file3.txt, file4.txt
// dir3 is a directory that contains file5.txt
// dir4 does not exist
// asynchronous function that checks if a file exists
function fileExists(file, callback) {
fs.access(file, fs.constants.F_OK, (err) => {
callback(null, !err);
});
}
// Using callbacks
async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,
function(err, result) {
console.log(result);
// true
// result is true since some file in the list exists
}
);
async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,
function(err, result) {
console.log(result);
// false
// result is false since none of the files exists
}
);
// Using Promises
async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)
.then( result => {
console.log(result);
// true
// result is true since some file in the list exists
}).catch( err => {
console.log(err);
});
async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)
.then( result => {
console.log(result);
// false
// result is false since none of the files exists
}).catch( err => {
console.log(err);
});
// Using async/await
async () => {
try {
let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);
console.log(result);
// true
// result is true since some file in the list exists
}
catch (err) {
console.log(err);
}
}
async () => {
try {
let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);
console.log(result);
// false
// result is false since none of the files exists
}
catch (err) {
console.log(err);
}
}
- Source:
(static) someLimit(coll, limit, iteratee, callbackopt) → {Promise}
import someLimit from 'async/someLimit';
The same as some
but runs a maximum of limit
async operations at a time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
limit |
number
|
The maximum number of async operations at a time. |
iteratee |
AsyncFunction
|
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). |
Returns:
a promise, if no callback provided
-
Type
-
Promise
- Source:
- See:
-
(static) someSeries(coll, iteratee, callbackopt) → {Promise}
import someSeries from 'async/someSeries';
The same as some
but runs only a single async operation at a time.
- Alias:
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
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). |
Returns:
a promise, if no callback provided
-
Type
-
Promise
- Source:
- See:
-
(static) sortBy(coll, iteratee, callback) → {Promise}
import sortBy from 'async/sortBy';
Sorts a list by the results of running each coll
value through an async
iteratee
.
Parameters:
Name |
Type |
Description |
coll |
Array
|
Iterable
|
AsyncIterable
|
Object
|
A collection to iterate over. |
iteratee |
AsyncFunction
|
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). |
Returns:
a promise, if no callback passed
-
Type
-
Promise
Example
// bigfile.txt is a file that is 251100 bytes in size
// mediumfile.txt is a file that is 11000 bytes in size
// smallfile.txt is a file that is 121 bytes in size
// asynchronous function that returns the file size in bytes
function getFileSizeInBytes(file, callback) {
fs.stat(file, function(err, stat) {
if (err) {
return callback(err);
}
callback(null, stat.size);
});
}
// Using callbacks
async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes,
function(err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
// results is now the original array of files sorted by
// file size (ascending by default), e.g.
// [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
}
}
);
// By modifying the callback parameter the
// sorting order can be influenced:
// ascending order
async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) {
getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {
if (getFileSizeErr) return callback(getFileSizeErr);
callback(null, fileSize);
});
}, function(err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
// results is now the original array of files sorted by
// file size (ascending by default), e.g.
// [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
}
}
);
// descending order
async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) {
getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {
if (getFileSizeErr) {
return callback(getFileSizeErr);
}
callback(null, fileSize * -1);
});
}, function(err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
// results is now the original array of files sorted by
// file size (ascending by default), e.g.
// [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt']
}
}
);
// Error handling
async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes,
function(err, results) {
if (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
} else {
console.log(results);
}
}
);
// Using Promises
async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes)
.then( results => {
console.log(results);
// results is now the original array of files sorted by
// file size (ascending by default), e.g.
// [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
}).catch( err => {
console.log(err);
});
// Error handling
async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes)
.then( results => {
console.log(results);
}).catch( err => {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
});
// Using async/await
(async () => {
try {
let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);
console.log(results);
// results is now the original array of files sorted by
// file size (ascending by default), e.g.
// [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
}
catch (err) {
console.log(err);
}
})();
// Error handling
async () => {
try {
let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);
console.log(results);
}
catch (err) {
console.log(err);
// [ Error: ENOENT: no such file or directory ]
}
}
- Source:
import transform from 'async/transform';
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 |
iteratee |
AsyncFunction
|
A function applied to each item in the
collection that potentially modifies the accumulator.
Invoked with (accumulator, item, key, callback). |
callback |
function
<optional>
|
A callback which is called after all the
iteratee functions have finished. Result is the transformed accumulator.
Invoked with (err, result). |
Returns:
a promise, if no callback provided
-
Type
-
Promise
Examples
// file1.txt is a file that is 1000 bytes in size
// file2.txt is a file that is 2000 bytes in size
// file3.txt is a file that is 3000 bytes in size
// helper function that returns human-readable size format from bytes
function formatBytes(bytes, decimals = 2) {
// implementation not included for brevity
return humanReadbleFilesize;
}
const fileList = ['file1.txt','file2.txt','file3.txt'];
// asynchronous function that returns the file size, transformed to human-readable format
// e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.
function transformFileSize(acc, value, key, callback) {
fs.stat(value, function(err, stat) {
if (err) {
return callback(err);
}
acc[key] = formatBytes(stat.size);
callback(null);
});
}
// Using callbacks
async.transform(fileList, transformFileSize, function(err, result) {
if(err) {
console.log(err);
} else {
console.log(result);
// [ '1000 Bytes', '1.95 KB', '2.93 KB' ]
}
});
// Using Promises
async.transform(fileList, transformFileSize)
.then(result => {
console.log(result);
// [ '1000 Bytes', '1.95 KB', '2.93 KB' ]
}).catch(err => {
console.log(err);
});
// Using async/await
(async () => {
try {
let result = await async.transform(fileList, transformFileSize);
console.log(result);
// [ '1000 Bytes', '1.95 KB', '2.93 KB' ]
}
catch (err) {
console.log(err);
}
})();
// file1.txt is a file that is 1000 bytes in size
// file2.txt is a file that is 2000 bytes in size
// file3.txt is a file that is 3000 bytes in size
// helper function that returns human-readable size format from bytes
function formatBytes(bytes, decimals = 2) {
// implementation not included for brevity
return humanReadbleFilesize;
}
const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' };
// asynchronous function that returns the file size, transformed to human-readable format
// e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.
function transformFileSize(acc, value, key, callback) {
fs.stat(value, function(err, stat) {
if (err) {
return callback(err);
}
acc[key] = formatBytes(stat.size);
callback(null);
});
}
// Using callbacks
async.transform(fileMap, transformFileSize, function(err, result) {
if(err) {
console.log(err);
} else {
console.log(result);
// { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
}
});
// Using Promises
async.transform(fileMap, transformFileSize)
.then(result => {
console.log(result);
// { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
}).catch(err => {
console.log(err);
});
// Using async/await
async () => {
try {
let result = await async.transform(fileMap, transformFileSize);
console.log(result);
// { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
}
catch (err) {
console.log(err);
}
}
- Source: