Iterate partial results of Promise.all

⚠️ This post uses latest JavaScript features. You'll need a modern browser or Node.js version 10 or higher to run examples.

I’ve stumbled upon this task while playing around with async iterators and for await...of statement.

From MDN about Promise.all:

The Promise.all() method returns a single Promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises.

What if we want to still run promises in parallel, but also output partial results along the way? This is useful for example in showing the status of asynchronous tasks in the UI.

Our new function will be called partialAll. What should it return? Since there would be multiple values over time, we can’t use a promise as a return value. And we’re too modern to use callbacks. Async iterators to the rescue:

We keep a pool of unresolved promises and Promise.race helps us to wait until the first one is done. Once done, it is removed from the pool. Since we don’t care about execution order we can use Set to track unresolved promises.