I’m using the fetch API in my JavaScript code to make a POST request to a specific endpoint. However, I’m encountering an issue where the fetch call seems to skip the .then() block entirely and goes straight to a return false statement. Here’s a simplified version of my code:
function login() {
var emailVar = email_input.value;
var senhaVar = senha_input.value;
if (emailVar == "" || senhaVar == "") {
return false;
}
console.log("FORM LOGIN: ", emailVar);
console.log("FORM SENHA: ", senhaVar);
fetch("/usuario/autenticar", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
emailServer: emailVar,
senhaServer: senhaVar
})
}).then(function (resposta) {
console.log("HERE'S IS THEN()!")
if (resposta.ok) {
console.log(resposta);
resposta.json().then(json => {
console.log(json);
console.log(JSON.stringify(json));
sessionStorage.EMAIL_USUARIO = json.email;
sessionStorage.NOME_USUARIO = json.nome;
sessionStorage.ID_USUARIO = json.id;
});
} else {
console.log("login error");
resposta.text().then(texto => {
console.error(texto);
});
}
}).catch(function (erro) {
console.log(erro);
})
return false;
}
The strange behavior I’m experiencing is that after the fetch call, specifically when it reaches the body: JSON.stringify(…) part, it goes straight to the return false statement without entering the .then() or .catch() blocks. I’ve checked the Network tab in my browser’s developer tools, and the request seems to be sent successfully with the expected JSON body.
I’m not sure why the fetch call is behaving this way and skipping the .then() block. Any insights or suggestions would be greatly appreciated. Thank you!
What I expected to happen was that after the fetch call, it would enter the .then() block, parse the JSON response, and set some session storage variables. However, what actually happened is that it skipped the .then() block entirely and went straight to the return false statement.
I’ve checked the Network tab in my browser’s developer tools, and the request seems to be sent successfully with the expected JSON response. The strange behavior is that the .then() block is not being executed at all.
2
Answers
you need to make your function
async
and useawait
when calling fetch (or any other awaitable/async functions). sorry don’t have enough score to comment. Lack of doing this would result in the behavior you described – i.e. skipping over to the next line.this is expected behavior.
fetch() is async and you are returning false after the fetch call, but the program will not wait for the fetch to complete.
For this situation: Don’t return false at the end, just do
and call the function like:
because you are returning a Promise. When doing this you should return the first false as a Promise:
I think you should read a bit more on Promises and async javascript, and maybe consider using typescript or some linters to help you.