From 8d071a6ee3c622f19d7e8fb661e269c18359f2b7 Mon Sep 17 00:00:00 2001 From: Michael Nahkies Date: Thu, 3 Sep 2015 12:00:45 +1200 Subject: [PATCH] Add definition and test for when.iterate --- when/when-tests.ts | 15 +++++++++++++++ when/when.d.ts | 14 ++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/when/when-tests.ts b/when/when-tests.ts index 6ed82dd32..7cd7e8e45 100644 --- a/when/when-tests.ts +++ b/when/when-tests.ts @@ -101,6 +101,21 @@ when.settle([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(resolve => resolve(5)); diff --git a/when/when.d.ts b/when/when.d.ts index 7ec721390..432a76b36 100644 --- a/when/when.d.ts +++ b/when/when.d.ts @@ -127,6 +127,20 @@ declare module When { */ function settle(promisesOrValues: any[]): Promise[]>; + /** + * 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(f: (seed: U) => U | Promise, + predicate: (value: U) => boolean, + handler: (value: U) => Promise | void, + seed: U | Promise): Promise; + + /** * Creates a {promise, resolver} pair, either or both of which * may be given out safely to consumers.