This is the code
const setError = "";
function validate() {
return new Promise((resolve, reject) => {
const exp = RegExp("w @example.com").test("[email protected]");
console.log(exp);
if (!exp) {
setError = "Email Not Valid!";
}
console.log("The value is" setError);
if (setError != "") {
reject();
} else {
resolve();
}
});
}
validate()
.then(() => {
console.log("Resolved");
})
.catch(() => {
console.log("Rejected");
});
When I run it, I get the following output,
false
Rejected
Why is the second console.log inside the validate function not executed?
CodePudding user response:
setError
should not be a const, when you try to change its value it throws an error and reject the Promise.
let setError = "";
CodePudding user response:
Because you are assigning to const setError
, it causes runtime error and stop the function execution.
const
cannot be re-assigned after initialization. Making it let
solves the problem
let setError = "";
function validate() {
return new Promise((resolve, reject) => {
const exp = RegExp("w @example.com").test("[email protected]");
console.log(exp);
if (!exp) {
setError = "Email Not Valid!";
}
console.log("The value is" setError);
if (setError != "") {
reject();
} else {
resolve();
}
});
}
validate()
.then(() => {
console.log("Resolved");
})
.catch(() => {
console.log("Rejected");
});
CodePudding user response:
The second console.log
is not firing because setError
is a constant and cannot be changed. Changing const
to let
should generate the output you expect:
false
The value isEmail Not Valid!
Rejected
CodePudding user response:
The reason why you are not seeing the second console.log
is because setError
is a const
, so as soon as you try to assign to it a new value, it throws an error and it will go to the catch
block.
Try this instead:
var setError = "";