Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
Java Script - Error handling in async/await

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 ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

In one liner I would say, you need to add return promise for each async function here is correct code.

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

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


const middleware = async () => {
  return 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");
  }
  Promise.resolve(true)
};

middleware();

Explanation:

Basically, the async function can be used with await, or in another word, you can say if you want to use await with any function then the function must be async that actually means the function should return a promise, then only can await statement can be justified.

Example:

Consider I’m calling a function “test()” and “await test()” so the difference between those two is in the first case (“test()”) it will call test function and if there are any blocking operations then it will continue with executing statements below “test()” statement. While in case of “await test()” if there is a blocking operation then it will wait for them to complete and not execute the further statements until the test function is completed (here completed means the function will return a promise and it will wait until the promise is resolved or rejected)

So here none of the async function returns a promise so by default as the function execution get over it consider it as resolved and because of that the problem is raised.

Detailed explanation with respect to this example.

The first “middleware()” function gets called. From that “addColor()” function get called

addColor():
if the promise return from this function get resolved then it will call “getColor()” function
Else it will just print an error message.

So it will first go to addColor function inside that function we are calling validateColor() function

validateColor():
If the promised return from this function is get resolved then we are adding the color to the array.
Else we print an error and throw it.

And validate color function throws an error because the color is null, but when it will come to else part of validate function (which is called from the addColor function) addColor function is already considered the execution is done successfully.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!