Hi all,
[Jake Archibald recently pointed out][1] that the promise returned by
`Promise.race` is rejected if any of the promises passed to `Promise.race`
get rejected before one was resolved. So in the following example:
```
var p = Promise.race([
new Promise(function(_, reject) { reject(new Error("boom!")); }),
new Promise(function(resolve) { setTimeout(resolve, 1000, "foo"); })
]);
```
`p` will be rejected with error `"boom!"` (instead of being resolved with
value "foo").
Although this seems to fit some use case, it doesn't work when the aim is
to resolve `p` with whichever promise resolves first and only reject `p`
when all promises have failed. For example, when doing a cache lookup and
racing it against the network, you want to display the data from whichever
source resolves first, and only display a fallback resource when neither
the cache nor the network are available.
In the same thread, [Tab Atkins mentioned][2] `Promise.any` fulfills this
use case and was briefly discussed within TC39 before being abandoned.
I'd imagine a pseudo implementation would look something like the below,
though you might want to surface all of the errors somehow.
```
Promise.any = function(promises) {
return new Promise(function(resolve, reject) {
var count = promises.length, resolved = false;
promises.forEach(function(p) {
Promise.resolve(p).then(function(value) {
resolved = true;
count--;
resolve(value);
}, function() {
count--;
if (count === 0 && !resolved) {
reject(new Error("No promises resolved successfully."))
}
});
});
});
};
```
Would TC39 be willing to (re)consider adding something like this to the
spec?
Thanks,
--tobie
---
[1]:
https://github.com/slightlyoff/ServiceWorker/issues/359#issuecomment-48605442
[2]:
https://github.com/slightlyoff/ServiceWorker/issues/359#issuecomment-49056388
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss