admin管理员组

文章数量:1420086

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");

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");
Share Improve this question edited May 23, 2017 at 12:00 CommunityBot 11 silver badge asked Nov 26, 2010 at 23:02 Marry HoffserMarry Hoffser 9551 gold badge8 silver badges5 bronze badges 1
  • So you effectively want to call the method synchronously? – thejh Commented Nov 26, 2010 at 23:05
Add a ment  | 

2 Answers 2

Reset to default 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.

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.

本文标签: javascriptLoop module for NodejsStack Overflow