node-async-loop
Loop through an array to execute asynchronous actions on each element.
Sometimes you must execute an asynchronous action on each elements of an array, but you must wait for the previous action to complete before proceed to the next.
Features:
- Loop through arrays
- Loop through objects
- Loop in the normal direction or in the reverse direction
- Error handling
- A callback is called for the end of the loop
Install
npm install --save node-async-loop
Function
var asyncLoop = ; ;
array: array
The array to loop
from (optionnal): integer
The starting position, including (Default: 0).
to (optionnal): integer
The final position, including (Default: array.length - 1).
callback: function(item, next)
The function called for every elements.
It must call next()
so that the next array element is executed.
At the end endCallback
will be called!
On error it must call next(errorObject)
and iteration will be stopped and the endCallback called with errorObject.
endCallback (optionnal): function(err)
This function is called at the end.
The err
variable is null if everything was fine, otherwise it contains the error.
Usage
Basic Usage
General usage:
var asyncLoop = ; var array = 'item0' 'item1' 'item2';;
For example, create folder recursively:
var fs = ;var asyncLoop = ; var directories = 'test' 'test/hello' 'test/hello/world';;
Loop Partially and in reverse order!
var asyncLoop = ; var { console; ;} var array = 'A' 'B' 'C' 'D' 'E' 'F'; // Loop all; // A, B, C, D, E, F; // A, B, C, D, E, F; // A, B, C, D, E, F // Loop partially to the end; // B, C, D, E, F; // C, D, E, F // Loop partially; // B, C, D; // A, B; // A, B, C // Loop partially in reverse order; // D, C, B; // B, B; // C, B, A // Loop partially, using negative from/to values// -1 is the last element (F)// -2 is the before last element (E)// -3 ... (D)// ...; // A, B, C, D, E; // B, C, D, E // So to loop in reverse order you can do; // F, E, D, C, B, A// or simply; // F, E, D, C, B, A// or simply simply; // F, E, D, C, B, A // Other examples; // E, D, C, B, A; // E, D, C; // C, D, E
Loop through objects
var asyncLoop = ; var obj = 'aa': 'AAAA' 'bb': 'BBBB' 'cc': 'CCCC' 'dd': 'DDDD' 'ee': 'EEEE'; ; // Output://// { key: 'aa', value: 'AAAA' }// { key: 'bb', value: 'BBBB' }// { key: 'cc', value: 'CCCC' }// { key: 'dd', value: 'DDDD' }// { key: 'ee', value: 'EEEE' }// Finished!