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.
Vishwa Bhat
Technology Enthusiast
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 Failedmessage will be executed only if_p3fails. Now,_p3will fail only if it executes insidep2.catch()andp2.catch()can execute only ifp1fails. So, if even one promise succeeds,All Failedmessage doesn't execute.And, I'm assuming all three promises have
.then(..)before this statement.Cheers!