-
Notifications
You must be signed in to change notification settings - Fork 0
Sequencr.promiseFor
Calls a function (callback) as if it was the body of a for loop, using promises to chain together each iteration. This is one of the most powerful features of Sequencr.js, and greatly enhances the functionality of native JavaScript promises.
startInclusive: The initial value of the iterator in the for loop (inclusive).
endExclusive: The final value of the iterator in the for loop (exclusive). Make sure this is finite because the promise chain needs to be set up all at once, so having an extremely large endExclusive can result in non-halting code. If endExclusive is less than or equal to startInclusive, Sequencr.promiseFor
will return a valueless resolved promise (aka, an empty promise :'( ).
callback: The function to call each iteration. Functions may accept four parameters: resolve
, reject
, i
, and value
. The callback should call either resolve
or reject
at some point, when it's work is done (read about promise usage). The i
parameter will contain the current iteration of the "for" loop. The value
parameter will contain the value passed to resolve of the previously called function (it will be undefined on the first iteration). Return values are ignored.
Basic Usage
//This will execute immediately, counting from 0 - 9 at 1s intervals.
var myPromise = Sequencr.promiseFor(0, 10,
(resolve, reject, i, value) => { //Note i is the iterator value (not used here).
setTimeout(() => {
if(!value) value = 0;
console.log(value);
value++;
resolve(value);
}, 1000);
}
);
//Whenever/later (optional; use if you need a done callback):
myPromise.then(() => {console.log("Done!"));
Breaking
Breaking out of a promise chain can be accomplished by calling reject function, created by JavaScript:
In this version of the library there are no infinite loops (or a promiseDo
function), because I'm not sure how you would go about setting up the promise-then chain for an indeterminate number of function calls. It's something I'll think about for a future version, and I'm open to suggestions.