Loop module for Node.js

A few minutes ago I asked about a loop; see Asynchronous Loop in JavaScript .

This time my question is: Is there any module for Node.js?

for ( /* ... */ ) {

  // Wait! I need to finish this async function
  someFunction(param1, praram2, function(result) {

    // Okay, continue

  })

}

alert("For cycle ended");
+5
source share
2 answers

Is it really difficult to move material to a module?

EDIT: Updated code.

function asyncLoop(iterations, func, callback) {
    var index = 0;
    var done = false;
    var loop = {
        next: function() {
            if (done) {
                return;
            }

            if (index < iterations) {
                index++;
                func(loop);

            } else {
                done = true;
                callback();
            }
        },

        iteration: function() {
            return index - 1;
        },

        break: function() {
            done = true;
            callback();
        }
    };
    loop.next();
    return loop;
}

exports.asyncFor = asyncLoop;

And a little test:

// test.js
var asyncFor = require('./aloop').asyncFor; // './' import the module relative

asyncFor(10, function(loop) {    
        console.log(loop.iteration());

        if (loop.iteration() === 5) {
            return loop.break();
        }
        loop.next();
    },
    function(){console.log('done')}
);

Rest is up to you, it is impossible to make this 100% shared.

+3
source

Yes, you can use Async.js .

Async - , , JavaScript. node.js, .

+1

All Articles