PromiseList is an extension to Promise.all() and Promise.race() and, more generally, a series of utilities around Promises.
Documentation
Promise.all()
returns a Promise
that succeeds only if all the
Promise
s succeed and Promise.race()
returns a Promise
that
succeeds when any Promise
succeeds. This extension add a new
function that returns a Promise
that succeeds when all the
Promise
s finished, no matter if they succeed or not.
Example 1: return all the results
Without any optional arguments, PromiseList
always succeeds. The result
is a list of [succeed, result]
pairs, where succeed
is a boolean
indicating if the related Promise
succeeded or not, and result
is
the related result.
var p1 = Promise;var p2 = Promise;var p3 = Promise;var pl = ; { for let succeed result of results if succeed ; else // probably an instance of Error ; }
Another example using Array.map and Array.filter:
var urls = /*...*/;var pl =
Example 2: mimic Promise.all()
PromiseList
resolves if all the Promise
s resolve or rejects if one
of them rejects.
From Mozilla's MDN:
Returns a promise that either resolves when all of the promises in the iterable argument have resolved or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise resolves, it is resolved with an array of the values from the resolved promises in the iterable. If the returned promise rejects, it is rejected with the reason from the promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises together.
The error, in case of failure, is always an instance of FirstError
.
var p1 = Promise;var p2 = Promise;var p3 = Promise;var pl = ;// eb(err) [=> err.failure === new Error("fail")]
Example 3: mimic Promise.race()
From Mozilla's MDN:
Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
var p1 = {}; // don't resolv or rejectvar p2 = Promise;var p3 = Promise;var pl = ;// cb(["2", 1])
Example 4: resolve with the first successful Promise
var p1 = Promise {}; // don't resolv or rejectvar p2 = Promise;var p3 = Promise;var pl = ;// cb(["3", 2])
trap()
trap()
is an utility to filter errors in a promise's catch clause.
Consider this code:
try ;catche if e instanceof IOError ; else if e instanceof TypeError ; else throw e;
Translated to asynchronous code with Promise
s and trap()
became:
{ ; ;} { ; ;}var promise = ;
execute()
Execute a function and return a Promise
:
{ return "sync";};
This function is useful if it is not known if a certain function returns
a Promise
or not.
{ return "sync";} { return Promise;}var promises = func1 func2;;
vim: tw=72