Promise.any is not a function?

I have a task that would greatly benefit its performance from using Promise.any() as defined here. Basically, I have an iterable object of promises, some of which fulfill, others reject. I just want to retrieve the returned value of the first one to fulfill.

However, I’m getting an error saying “Promise.any is not a function”. Promise.race and Promise.all work just fine. Is it possible that Promise.any isn’t supported by Meteor? If so, how can I get around this?

So, I found Promise.any() is not even part of ECMAScript yet… It’s currently a proposal for ES2021.

In any case, I found a solution for anyone like me looking to retrieve the first “success” from an array of promises and that is: invert the polarity of Promise.all(). Basically, throw a rejection for the first successfully solved call and a return a fulfilled/resolved promise for any “unsuccessful” calls. Your code will simply run until hits the rejection, which is your first successful call. You can even return a value in the Error object message, which is caught by the catch clause (you’ll have to stringify it and then parse it because the Error object is not iterable; it’s easier than it sounds).

Hmm,

Just did a quick test of this on my end and got the same results as you - Promise.any is not a function.

Interesting workaround though!

1 Like

You can declare your own Error type, to which you are free to pass any data. E.g.

class MyError extends Error {
 constructor(data) {
   this.data = data;
 }
}

…and then you just access error.data of an error object of this type. But you may not have to use this after all if you install a Promise.any polyfill, e.g. this one: https://www.npmjs.com/package/@ungap/promise-any

1 Like