Promise.all Exception Handling

by Luis Perez

JavaScript

myAll = (val) => {
  return new Promise(function(resolve, reject) {
    if (val > 0)
      resolve((val + 1) * 5)
    else if (val < 0)
      reject(val * 2)
    else {
      var tmp = new Error("No work for 0");
      tmp.type = 'CustomError';
      reject(tmp);
    }
  })
}
// .catch using Promise.all 
/* 
  Extrending to the catch block handling, Attempting to call the catch block 
   explicitly will fail. They will reject on the first fail case, so attempting
    to throw from the function that is calling, will not work. 
    For the purpose of maintianing the try/catch syntax, the Exception case
    is wrapped around a resolve in itself, which then throws the Error, which 
    is caught by the needed Catch Block.

*/
Promise.all([myAll(1), myAll(0), myAll(-3)])
  .then(
    arr => {
      for (var ind = 0; ind < arr.length; ind++) {
        console.log(arr)
      };
    }, rej => {
      if (rej.type == 'CustomError')
        throw rej;
      console.log(arr)
    })
  .catch(e => {
    console.log("Catching Internal ", e.message)
  })