Wednesday, 15 March 2017

How to make promises catch work?

Background

I am using Promises, and I have a multitude of functions that may or may not return a Promise and that may or may not fail, like in the example below:

//does not return a Promise, simply a string
let goodFun = function(){
    return "I like bananas!";
};

//blows up!
let badFun = function(){
    throw "A general error blaahh!"; 
};

//You get the point ...

Since these functions may or may not return Promises and may or may not fail, I need to wait for all of them to execute. To achieve this I have a function to call them all and wait for their execution:

let asyncFun = function(){
    return Promise.all([badFun(), goodFun()]);
};

Problem

So far so good. My code calls asyncFun and I expect some of its functions to actually fail. To be prepared, I added a catch:

let executor = function(){

    let numbsArray = [1, 2, 3];
    let respArray = [];

    for(let num of numbsArray){
        respArray.push(
            asyncFun()
                .catch( error => console.log(`I failed with ${error} and ${num}`))
        );
    }

    return Promise.all(respArray);
};

The problem is that catch is not catching anything at all!

Even adding a catch to the function calling the executor is not catching anything !

executor()
    .catch(error => console.log("Failed miserably to catch error!"));

Research

I don't really understand why my catch clauses are not catching the exception. To find out, I read this discussion:

Which leads me to believe that all my functions goodFun and badFun, no matter what, must always return a promise.

This is confusing for me, because according to the MDN documentation the array may contain a Promise, or a result from one (like a string, or a number).

I would also like to avoid adding even more boiler plate code to my functions ....

Question:

  1. How do I fix my code, so the catches work adding a minimum or boilerplate code?

Code

let goodFun = function() {
  return "I like bananas!";
};

let badFun = function() {
  throw "A general error blaahh!";
};



let asyncFun = function() {
  return Promise.all([badFun(), goodFun()]);
};

let executor = function() {

  let numbsArray = [1, 2, 3];
  let respArray = [];

  for (let num of numbsArray) {
    respArray.push(
      asyncFun()
      .catch(error => console.log(`I failed with ${error} and ${num}`))
    );
  }

  return Promise.all(respArray);
};

executor()
  .catch(error => console.log("Failed miserably to catch error!"));


via Flame_Phoenix

No comments:

Post a Comment