Merge pull request #5656 from mnahkies/when-iterate

Add definition and test for when.iterate
This commit is contained in:
Masahiro Wakame
2015-09-08 21:42:01 +09:00
2 changed files with 29 additions and 0 deletions
+15
View File
@@ -101,6 +101,21 @@ when.settle<number>([when(1), when(2), when.reject(new Error("Foo"))]).then(desc
return descriptors.filter(d => d.state === 'rejected').reduce((r, d) => r + d.value, 0);
});
/* when.iterate(f, predicate, handler, seed) */
when.iterate(function (x) {
return x + 1;
}, function (x) {
// Stop when x >= 100000000000
return x >= 100000000000;
}, function (x) {
console.log(x);
}, 0).done(function (x) {
console.log(x === 100000000000);
}, function (err) {
console.log(err);
});
/* when.promise(resolver) */
promise = when.promise<number>(resolve => resolve(5));
+14
View File
@@ -127,6 +127,20 @@ declare module When {
*/
function settle<T>(promisesOrValues: any[]): Promise<Descriptor<T>[]>;
/**
* Generates a potentially infinite stream of promises by repeatedly calling f until predicate becomes true.
* @memberOf when
* @param f function that, given a seed, returns the next value or a promise for it.
* @param predicate function that receives the current iteration value, and should return truthy when the iterating should stop
* @param handler function that receives each value as it is produced by f. It may return a promise to delay the next iteration.
* @param seed initial value provided to the handler, and first f invocation. May be a promise.
*/
function iterate<U>(f: (seed: U) => U | Promise<U>,
predicate: (value: U) => boolean,
handler: (value: U) => Promise<any> | void,
seed: U | Promise<U>): Promise<U>;
/**
* Creates a {promise, resolver} pair, either or both of which
* may be given out safely to consumers.