Hi I am kinda new to js and its hard for me to understand that code can execute before the code before him finished, so here is my problem:
I have a function that logs in a user to a server based on the provided email and password (the server pard works) and I want to wait for the function to return a bool value:
if (logInUser(userToLogin)){
// do something if succes
console.log("loged in")
}else{
// do something if not login
console.log("not logged in")
}
here is the function:
this function sends a post request to an API and based on the response return true or false
const logInUser = (user) => {
fetch("/api/login", { method: "POST", body: JSON.stringify(user)})
.then(data => {
console.log(data.status)
if (data.status === 201){
return true;
}else if(data.status === 401){
alert("check email and password and try again");
return false;
}else{
alert("unknown error try again");
return false;
};
});
};
so no matter what I send it will console.log(“not logged in”) although the login process was a success:
when I send the correct email and password
as u can see the response was 201, the user logged in but the console log “not logged in”.
here is the response I get when I give a random email and value the log also happens before I get the response.
so how can I make the if statements wait for the “logInUser: function to finish
I tried adding await like so:
if (await logInUser(userToLogin)){
// do something if succes
console.log("loged in")
}else{
// do something if not login
console.log("not logged in")
} here
but it’s not working.