Promise.any

Mark S. Miller erights at google.com
Thu Jul 17 13:56:41 PDT 2014


On Thu, Jul 17, 2014 at 9:28 AM, Tobie Langel <tobie.langel at gmail.com>
wrote:

> 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?
>

For ES7, sure, this is something we can consider. ES6 promises
intentionally have a small API surface -- a much smaller one than I expect
for ES7 promises. As for what should be added, that will of course be an
extended discussion. Happy to see it start here.




>
> 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
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>


-- 
    Cheers,
    --MarkM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140717/da153d3c/attachment.html>


More information about the es-discuss mailing list