wayofthefuture wayofthefuture - 2 months ago 7
Javascript Question

Execute a promise loop and catch errors along the way

So here is a true beauty from @Roamer-1888:

executePromiseLoop(myArray).catch(logError).then(() => console.log('yay!'));

function executePromiseLoop(arr) {
return arr.reduce(function(promise, email) {
return promise.then(function() {
return myCustomPromise(email);
});
}, Promise.resolve());
}


It's a promise loop that executes serially. There are two concerns I have:


  1. What happens if a promise in the loop fails, does it quit the loop?

  2. Should I implement a catch inside the loop, or will a fail propagate back up to the calling function?



Should I insert a catch in the loop?

function executePromiseLoop(arr) {
return arr.reduce(function(promise, email) {
return promise.catch(logError).then(function() {
return myCustomPromise(email);
});
}, Promise.resolve());
}

Answer

What happens if a promise in the loop fails, does it quit the loop?

Yes. If a single promise is rejected, all the next promises will not be executed. See this code for example:

Promise.resolve()
  .then(Promise.reject)
  .then(() => console.log('this will not be executed'))
  .catch(() => console.log('error'))

The promise in the third line will not be executed, because the promise before it was rejected.

Should I implement a catch inside the loop, or will a fail propagate back up to the calling function?

The reject message will propagate, so you don't need to use a catch inside the loop. See this code for example:

Promise.resolve()
  .then(() => Promise.resolve())
  .then(() => Promise.reject('something went wrong'))
  .then(() => Promise.resolve())
  .then(() => Promise.resolve())
  .catch(error => console.log(error))