for-async v1.0.0
Helper function to ease doing async work in a loop
Installation
npm install --save for-async
Dependencies and imports
for-async has no dependencies. Load it like this:
;
Or, using ES5 / require
:
var forAsync = ;
Also usable in the browser, but because for-async
is tiny, you're probably better off
by just copying the function from the source directly.
Usage
/** * Loops over an array, performing (async) work on each item. * * arr The (possibly empty) array to loop over. * fn The callback function that will be called for each item. * It has the signature `fn(item, idx)`, where `item` is the * current array element and `idx` is the index in the array. */
Use forAsync
as you would forEach
, except it's not a method of Array
but a separate function,
so pass the array to loop over as the first parameter.
Sync Usage
For convenience, forAsync
can be used with sync as well as async callback functions:
var arr = 'some' 'cool' 'array';
Async Usage
You can do async work inside the callback function by having it return a Promise:
var arr = 'some' 'cool' 'array';
The next iteration will only start when the promise returned by the previous iteration has fulfilled.
If we are calling a function that already returns a Promise
, we don't have to wrap it in another
Promise
, but can just return the result directly:
{ return { ; // delay 25 ms to make async }} var arr = 'some' 'cool' 'array'; // Or, even shorter: ;
Waiting for the loop to complete
forAsync
itself returns a Promise
, that we can use to wait for the loop to complete:
var arr = 'some' 'cool' 'array';var result = '';console;// logs an empty line
If it surprises you that the last statement logs an empty line, learn more about async.
Breaking off the loop
The loop will be broken off when an exception is thrown (in the case of sync code), or when the
Promise
returned from async code is rejected:
var arr = 'some' 'cool' 'array';
Catching thrown errors or rejected promises
Just like we used the then
method on the Promise
returned by forEach
to wait for the loop to
complete, we can use the catch
method to catch any errors that happened:
var arr = 'some' 'cool' 'array';
Passing information from one loop iteration to the next
There is no mechanism built into forAsync
for exchanging
data between the different loop iterations, but Javascript makes
this very simple anyway, by using a variable in the enclosing
scope:
let x = 10;var arr = 10 25 55;
Feedback, suggestions, questions, bugs
Please visit the issue tracker for any of the above. Don't be afraid about being off-topic. Constructive feedback most appreciated!
Copyright
© 2016, Stijn de Witt. Some rights reserved.