Search code examples
javascriptnode.jses6-promise

p-any versus Promise.any


Problem

The p-any package suggests that it is a replacement for Promise.race given this link as a reason. As p-any suggest, it does seem it like is a better option in most scenarios, however Promise.any seems to do the same thing.

My understanding

Promise.race takes an Iterable of promises and returns the first promise that completes with either an error or resolution.

Promise.any returns the first promise that resolves, and ignores failures.

Help

Is my understanding correct? Do p-any and Promise.any do the same thing? Thanks for your help


Solution

  • If your question is whether p-any's any function and the standard Promise.any function do the same thing, then based on p-any's documentation, yes, they do. They both get fulfilled when the first promise from the iterable gets fulfilled, or get rejected with an AggregateError if all of the promises from the iterable get rejected.

    Promise.any is still just a Stage 3 proposal, though it's likely to hit Stage 4 very soon. p-any and similar presumably predate that effort slightly.

    This chart (I wish SO's markdown allowed tables!) may be useful for understanding the different Promise combinators:

    +−−−−−−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−+
    | Name               | Description                                     | Added In         |
    +−−−−−−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−+
    | Promise.allSettled | does not short−circuit                          | ES2020           |
    | Promise.all        | short−circuits when an input value is rejected  | ES2015           |
    | Promise.race       | short−circuits when an input value is settled   | ES2015           |
    | Promise.any        | short−circuits when an input value is fulfilled | Stage 3 proposal |
    +−−−−−−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
    

    This article the proposal links to may as well.