Explanation | Checking if all promises fail?

I'm reading Service Worker Offline Cookbook. Following is a piece of code, that checks if all promises have rejected โ€”

/*  inside a promise */
/* reject if all promises reject */

promises.reduce((a, b) => a.catch(() => b))
    .catch(() => reject(Error('All Failed'))

I do not understand how a.catch(() => b) inside a reduce is ensuring to tell the information of failure of promises.

Comments (2)

Vishwa Bhat's photo

Let's do a dry run:

const promises = [ p1, p2, p3 ];

promises.reduce((a, b) => a.catch(() => b))
    .catch(() => reject(Error('All Failed'))

The above code is equivalent to:

const _p3 = p1.catch(() => p2.catch(() => p3));

_p3.catch(() => reject(Error('All Failed'))

So, let's traverse backwards. All Failed message will be executed only if _p3 fails. Now, _p3 will fail only if it executes inside p2.catch() and p2.catch() can execute only if p1 fails. So, if even one promise succeeds, All Failed message doesn't execute.

And, I'm assuming all three promises have .then(..) before this statement.


Arihant's photo

I have no idea how I missed how reduce works ๐Ÿคฆโ€โ™‚๏ธ. Thank you! ๐Ÿ’›