JavaScript Sync/Async forEach
An optionally-asynchronous forEach with an interesting interface.
Getting Started
This code should work just fine in Node.js:
First, install the module with: npm install async-foreach
var forEach = forEach;;// logs:// each a 0 ["a", "b", "c"]// each b 1 ["a", "b", "c"]// each c 2 ["a", "b", "c"]
Or in the browser:
In the browser, you can attach the forEach method to any object.
The General Idea (Why I thought this was worth sharing)
The idea is to allow the callback to decide at runtime whether the loop will be synchronous or asynchronous. By using this
in a creative way (in situations where that value isn't already spoken for), an entire control API can be offered without over-complicating function signatures.
; ; ; ;
Examples
See the unit tests for more examples.
// Generic "done" callback. { console;} // Synchronous.;// logs:// each a 0 ["a", "b", "c"]// each b 1 ["a", "b", "c"]// each c 2 ["a", "b", "c"]// done true ["a", "b", "c"] // Synchronous with early abort.;// logs:// each a 0 ["a", "b", "c"]// each b 1 ["a", "b", "c"]// done false ["a", "b", "c"] // Asynchronous.;// logs:// each a 0 ["a", "b", "c"]// each b 1 ["a", "b", "c"]// each c 2 ["a", "b", "c"]// done true ["a", "b", "c"] // Asynchronous with early abort.;// logs:// each a 0 ["a", "b", "c"]// each b 1 ["a", "b", "c"]// done false ["a", "b", "c"] // Not actually asynchronous.;// logs:// each a 0 ["a", "b", "c"]// each b 1 ["a", "b", "c"]// each c 2 ["a", "b", "c"]// done true ["a", "b", "c"] // Not actually asynchronous with early abort.;// logs:// each a 0 ["a", "b", "c"]// each b 1 ["a", "b", "c"]// done false ["a", "b", "c"]
Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using grunt.
Also, please don't edit files in the "dist" subdirectory as they are generated via grunt. You'll find source code in the "lib" subdirectory!
Release History
04/29/2013 v0.1.3 Removed hard Node.js version dependency.
11/17/2011 v0.1.2 Adding sparse array support. Invalid length properties are now sanitized. This closes issue #1 (like a boss).
11/11/2011 v0.1.1 Refactored code to be much simpler. Yay for unit tests!
11/11/2011 v0.1.0 Initial Release.
License
Copyright (c) 2012 "Cowboy" Ben Alman
Licensed under the MIT license.
http://benalman.com/about/license/