2.8 KiB
forEachAsync
Analogous to [].forEach, but handles items asynchronously with a final callback passed to then.
This is the most essential piece of the ArrayAsync package.
v5.x
We jumped from 3.x to 5.x because I'm considering creating a backwards-and-forwards compatible 4.x that uses AngularJS-style function introspection to allow for having the next param. Straight up, that's probably a bad idea and waste of time so I hope I don't actually do it.
Usage
// EXAMPLE ASYNC FUNCTION
function getPicsAsync(animal) {
var flickerApi = "http://api.flickr.com/services/feeds/photos_public.gne?tagmode=any&format=json&tags=" + animal;
return requestAsync({ url: flickerApi });
}
forEachAsync(['dogs', 'cats', 'octocats'], function (element) {
return getPicsAsync(element);
}).then(function () {
// then after all of the elements have been handled
// the final callback fires to let you know it's all done
console.log('All requests have finished');
});
Supplying your own Promises Implementation
If native ES6 promises are not available, then you should supply your own Promises/A+ implementation like so:
forEachAsync = forEachAsync.create(window.Promise || require('bluebird'));
Browser Installation
You can install from bower:
bower install --save forEachAsync@5.x
Or download the raw file from https://raw.github.com/FuturesJS/forEachAsync/master/forEachAsync.js:
wget https://raw.github.com/FuturesJS/forEachAsync/master/forEachAsync.js
(function () {
'use strict';
var forEachAsync = window.forEachAsync
;
// do stuff ...
}());
Note: If you need both 3.x/4.x and 5.x version of forEachAsync in the browser... good luck with that...
Node Installation
npm install --save forEachAsync@5.x
API
forEachAsync(array, callback[, thisArg])
Parameters
arrayArray of elements to iterate overcallbackFunction to execute for each element, takes 4 argumentselementa single element of the aforementioned arrayindexthe index of the current elementarraythe same array mentioned above
thisArgObject to use asthiswhen executingcallback
forEachAsync#then(done)
Parameters
thenis in the return value offorEachAsyncand accepts a finaldonecallback.donecalled afterforEachAsyncis complete, takes no arguments
Internal API
forEachAsync.__BREAK
This is used internally for the purposes of the ArrayAsync library.
Please don't break stuff; use ArrayAsync.someAsync or ArrayAsync.everyAsync instead.