I am a beginner in javascript and recently delved into async/await. After going through various resources, I gained a basic understanding. However, while experimenting with some code examples, I encountered unexpected results which left me puzzled about where I went wrong.
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();
Upon executing the middleware function, instead of only displaying the error message as expected, the output included the names of colors as well. Output:
https://i.sstatic.net/YfIPM.png
I am perplexed as to why the code inside then() is being executed even when addColor() throws an error. Furthermore, it's puzzling why the catch block within middleware() is not being triggered.