5

Few minutes ago I asked about looping, see Asynchronous for cycle 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");
Community
  • 1
  • 1
Marry Hoffser
  • 957
  • 1
  • 8
  • 5

2 Answers2

3

Is is that hard to move the stuff over into a module?

EDIT: Updated the 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 small 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's impossible to make this 100% generic.

Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112
  • No, it isn't. I just wanted to know if there is something especially for Node.js. Anyway, thank you again! – Marry Hoffser Nov 26 '10 at 23:25
  • I don't know of any such module, you have to write your own one for such generic functions, normally you use a completely different approach to avoid the need of such "async for loops" altogether. But the solutions differ vastly depending on the type of the problem. – Ivo Wetzel Nov 26 '10 at 23:30
1

Yes, you can use Async.js.

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with node.js, it can also be used directly in the browser.

Baggz
  • 17,207
  • 4
  • 37
  • 25
  • 1
    Took a quick look at it, but what she wants to do can't be exactly reproduced in `async.js`. She wants to block until the callback has finished and that for X times. The queue would come close though, but it would need some changes to the code she has right now. Also she has another callback inside her function which again makes it a bit more complicated. – Ivo Wetzel Nov 27 '10 at 00:29