-
Notifications
You must be signed in to change notification settings - Fork 1
async.whilst
Eugene Lazutkin edited this page Mar 19, 2016
·
2 revisions
This modules provides a functionality of a generalized asynchronous loop. It takes up to three arguments:
-
pred()
— a predicate function (possibly asynchronous) that for a given value returns a truthy or falsy value. A truthy value continues a loop, while a falsy value stops it, and resolves a final promise to the last value. -
body()
— an optional function (possibly asynchronous) that takes a value, and returns another (or same) value. If it is not specified or falsy, the result ofpred()
is going to be used as a result of an interation. -
Deferred
— an optional deferred constructor for internal promises (realistically Deferred or FastDeferred), or a falsy value to use the standardPromise
.
It returns a function that takes one argument (an arbitrary value) to start an asynchronous loop, and returns a promise.
Example (with synchronous functions for simplicity):
var whilst = require('heya-async/whilst');
// calculate a factorial
var loop = whilst(
function (tuple) { // pred
return tuple[0] > 0;
},
function (tuple) { // body
return [tuple[0] - 1, tuple[1] * tuple[0]];
}
);
loop([6, 1]).then(function (tuple) {
console.log(tuple[0] + '! = ' + tuple[1]); return tuple;
});