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
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
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
}
);
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 passesasync.until
will call the function each time the test fails 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
}
);