Home > Mobile >  Java Script - Error handling in async/await
Java Script - Error handling in async/await

Time:12-09

I am new to javascript and I was learning about async/ await. I studied through different document and got basic idea. While running some example I faced some unexpected result. I am not sure where did I miss.

Code:

var colors = ["RED", "GREEN", "YELLOW"];

const getColor = async () => {
  var value = "";
  colors.forEach((color) => {
    value = value   color   " ";
  });
  return value;
};


const middleware = async () => {
  addColor(null)
    .then(() => {
      getColor().then((result) => {
        console.log(result);
      });
    })
    .catch((err) => {
      console.log(err.message   " at  middleware");
    });
};

const addColor = async (color) => {
  validateColor(color)
    .then(() => {
      console.log("Adding data");
      colors.push(color);
    })
    .catch((err) => {
      console.log(err.message   " at add color");
      throw err;
    });
};

const validateColor = async (color) => {
  if (color == null) {
    throw new Error("Color cannot be empty");
  }
};

middleware();



After calling the middleware function , the expected result was to print the error message only . But it print the name of colors as well. Output:

enter image description here

I am not able to understand why the code inside then() was executed even though the addColor() is throwing some error? Also, why the catch block at middleware() is not being called ?

CodePudding user response:

Both validateColor() and addColor() create Promise objects, but they are unrelated. If addColor() is changed to return the Promise from validateColor(), your code works as you expect:

    var colors = ["RED", "GREEN", "YELLOW"];
    
    const getColor = async () => {
      var value = "";
      colors.forEach((color) => {
        value = value   color   " ";
      });
      return value;
    };
    
    
    const middleware = async () => {
      addColor(null)
        .then(() => {
          getColor().then((result) => {
            console.log(result);
          });
        })
        .catch((err) => {
          console.log(err.message   " at  middleware");
        });
    };
    
    const addColor = async (color) => {
      return validateColor(color)
        .then(() => {
          console.log("Adding data");
          colors.push(color);
        })
        .catch((err) => {
          console.log(err.message   " at add color");
          throw err;
        });
    };
    
    const validateColor = async (color) => {
      if (color == null) {
        throw new Error("Color cannot be empty");
      }
    };
    
    middleware();

Your async functions result in the return value being wrapped in a Promise. Thus both validateColor() and addColor() will, unless you do something about it, create separate individual Promise objects that have nothing to do with each other. On the other hand, if addColor returns the Promise that validateColor() returns, then there will not be a separate new Promise created; the same Promise is passed back to middleware(). That Promise has the pending exception thrown in validateColor(), so the .catch() will be called.

  • Related