Git Product home page Git Product logo

javascript-sync-async-foreach's Introduction

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 = require('async-foreach').forEach;
forEach(["a", "b", "c"], function(item, index, arr) {
  console.log("each", item, index, arr);
});
// logs:
// each a 0 ["a", "b", "c"]
// each b 1 ["a", "b", "c"]
// each c 2 ["a", "b", "c"]

Or in the browser:

<script src="dist/ba-foreach.min.js"></script>
<script>
forEach(["a", "b", "c"], function(item, index, arr) {
  console.log("each", item, index, arr);
});
// logs:
// each a 0 ["a", "b", "c"]
// each b 1 ["a", "b", "c"]
// each c 2 ["a", "b", "c"]
</script>

In the browser, you can attach the forEach method to any object.

<script>
this.exports = Bocoup.utils;
</script>
<script src="dist/ba-foreach.min.js"></script>
<script>
Bocoup.utils.forEach(["a", "b", "c"], function(item, index, arr) {
  console.log("each", item, index, arr);
});
// logs:
// each a 0 ["a", "b", "c"]
// each b 1 ["a", "b", "c"]
// each c 2 ["a", "b", "c"]
</script>

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.

forEach(arr, function(item, index) {
  // Synchronous.
});

forEach(arr, function(item, index) {
  // Only when `this.async` is called does iteration becomes asynchronous. The
  // loop won't be continued until the `done` function is executed.
  var done = this.async();
  // Continue in one second.
  setTimeout(done, 1000);
});

forEach(arr, function(item, index) {
  // Break out of synchronous iteration early by returning false.
  return index !== 1;
});

forEach(arr, function(item, index) {
  // Break out of asynchronous iteration early...
  var done = this.async();
  // ...by passing false to the done function.
  setTimeout(function() {
    done(index !== 1);
  });
});

Examples

See the unit tests for more examples.

// Generic "done" callback.
function allDone(notAborted, arr) {
  console.log("done", notAborted, arr);
}

// Synchronous.
forEach(["a", "b", "c"], function(item, index, arr) {
  console.log("each", item, index, arr);
}, allDone);
// 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.
forEach(["a", "b", "c"], function(item, index, arr) {
  console.log("each", item, index, arr);
  if (item === "b") { return false; }
}, allDone);
// logs:
// each a 0 ["a", "b", "c"]
// each b 1 ["a", "b", "c"]
// done false ["a", "b", "c"]

// Asynchronous.
forEach(["a", "b", "c"], function(item, index, arr) {
  console.log("each", item, index, arr);
  var done = this.async();
  setTimeout(function() {
    done();
  }, 500);
}, allDone);
// 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.
forEach(["a", "b", "c"], function(item, index, arr) {
  console.log("each", item, index, arr);
  var done = this.async();
  setTimeout(function() {
    done(item !== "b");
  }, 500);
}, allDone);
// logs:
// each a 0 ["a", "b", "c"]
// each b 1 ["a", "b", "c"]
// done false ["a", "b", "c"]

// Not actually asynchronous.
forEach(["a", "b", "c"], function(item, index, arr) {
  console.log("each", item, index, arr);
  var done = this.async()
  done();
}, allDone);
// 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.
forEach(["a", "b", "c"], function(item, index, arr) {
  console.log("each", item, index, arr);
  var done = this.async();
  done(item !== "b");
}, allDone);
// 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/

javascript-sync-async-foreach's People

Contributors

cowboy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

javascript-sync-async-foreach's Issues

async forEach breaks when items exceed 2050 in an array.

I wanted to asynchronously loop through 10000 items. It broke. I kept on decreasing the items until I reached 2050. It runs successfully when items are <=2050 but not >2050.
It showed me this:
Error: at next (...\node_modules\async-foreach\lib\foreach.js:46:23)
I was unable to read the complete error as the console had an overflow of this error.
It kept repeating the same line over and over...

Though when I removed the this.async line, it ran perfectly.

Add ability to not break early

At the moment when you call done(false) it will break out the loop early. It would be nice to have an option of being able to continue iterating, something like alwaysContinue. What do you think?

var forEach = require('async-foreach').forEach;

var complete = function(passed, arr) {
    console.log(passed, passedCount); // Would like it to echo: 'false / 2'
};

var passedCount = 0;
forEach(['pass', 'fail', 'pass'], function(item) {
    var done = this.async();
    if (item == 'pass') {
        passedCount++;
        done();
    } else {
        done(false);
    }
}, complete, {
    alwaysContinue: true
});

control does not wait for asynchrounous calls in foreach to complete

I am trying to use this in an API call:


        forEach(["a", "b", "c"], function(item, index, arr) {
            var done = this.async();
        console.log("each", item, index, arr);
              setTimeout(function() {
              done();
            }, 500);
          }, function(){
              console.log("all done demo")
          }
        );
        
          console.log("END OF FOREACH")

here's what console looks like:

 each a 0 [ 'a', 'b', 'c' ]

 END OF FOREACH  //as soon as it reaches this point, it returns to the calling function. 

each b 1 [ 'a', 'b', 'c' ]

each c 2 [ 'a', 'b', 'c' ]

I essentially wanted to calculate some values in the foreach callback and return to calling the function from there. How do I get that working?

Add sparse array support like a boss.

For extra bonus points you should make this method closer to the ES5.1 one.
So this:

forEach(arr, eachFn, doneFn)

would become

forEach(object, callback [, options]);

options would have callback params like onDone as well as a bound prop or something.

Also, internally you should resolve length like var length = object.length >>> 0; and support sparse arrays (in operator checks).

I have a method similar to this in benchmark.js (also allows async calling).

Explain what this library does in the README.md

Explain what this library does in the README.md.

Looking at the examples, it shows the same output for every demo so I am trying to figure out just what this library does. Can someone explain a little better please and thank you?

It says:

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.

So what does this mean exactly? As in what is the actual visual difference of the 2?

the loop will be synchronous or asynchronous

Looking for a maintainer?

Package seems to be used widely but can't see a lot of commits in the past โœ๏ธ.

Would be happy to jump in, if you wish. ๐Ÿ˜

Cheers,
Stefan

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.