15

Greeting all,

I want to call a function repeatedly, but wanted each call to run only when the previous call is completed. Does the Async's whilst fit what I need? Or do the calls happen in parallel?

Thanks!

Gary

Gary
  • 483
  • 2
  • 6
  • 17

3 Answers3

34

Whilst will do what you need, it runs each function in series. Before each run it will do the "test" function to make sure it should run again.

Their example:

var count = 0;

async.whilst(
    function () { return count < 5; },
    function (callback) {
        count++;
        setTimeout(callback, 1000);
    },
    function (err) {
        // 5 seconds have passed
    }
);
Chad
  • 19,219
  • 4
  • 50
  • 73
  • 1
    the structure of this whilst example has changed, check the documentation https://caolan.github.io/async/v3/docs.html#whilst – o1sound Oct 13 '19 at 03:59
2

As Chad noted, Async's whilst will do the job.

You may want to consider Async's until (inverse of whilst). Both do the same job however the key difference is:

  • async.whilst will call the function each time the test passes
  • async.until will call the function each time the test fails
Community
  • 1
  • 1
0

Async's whilst should do the trick for you. Please note the version of async you will be using before referring to the code on the accepted answers. As one of the comments in the accepted answer suggests, the structure of this loop has slightly changed which might not be very easy to spot.

Async v2: Accepted Answer

Async v3: https://caolan.github.io/async/v3/docs.html#whilst

Their Example:

var count = 0;
async.whilst(
    function test(cb) { cb(null, count < 5); },
    function iter(callback) {
        count++;
        setTimeout(function() {
            callback(null, count);
        }, 1000);
    },
    function (err, n) {
        // 5 seconds have passed, n = 5
    }
);
Sagar Ganiga
  • 430
  • 4
  • 8