2
My goal is to get the user’s email and then send it to the database. For this, I put a "change" event in the input that captures the email. My idea is that every time the input goes out of focus, the value within the input is captured.
Filing cabinet index.js
:
const GetEmail = require("./classes/getEmail.js");
(async function () {
const email = await new GetEmail().userEmail;
console.log('email retornado no index.js');
})();
Filing cabinet getEmail.js
:
get userEmail() {
return new Promise((resolve, reject) => {
const input = document.querySelector(".email-form input");
function handleInputChange({ target: { value: email } }) {
console.log('evento change disparado');
console.log('email: ' + email);
if (this.validateEmail(email)) {
console.log('email correto, resolve deve ser retornado');
return resolve(email);
} else {
console.log('email incorreto, reject deve ser retornado');
return reject("Invalid e-mail");
}
}
handleInputChange = handleInputChange.bind(this);
input.addEventListener("change", handleInputChange);
});
}
The problem is this: if I type the email incorrectly and take the focus of the input, the promise within the userEmail method returns the Reject and an error message is sent to the browser console (this behavior is expected). But if I turn the focus to input and correct the email, the Promise Does NOT return the resolve with the email and function console.log
within the index.js
IS NOT EXECUTED.
Follow a Gif demonstrating this behavior: https://imgur.com/gb6d040
Conversely, if I type the email correctly and take the focus of the input, the promise within the method userEmail
returns the solves with the email and the function console.log
within the index.js
is executed correctly. But if I change the email to an incorrect one, the Promise should return the reject
that should throw an error in the browser console, but that’s not what happens.
Follow another gif demonstrating the above behavior: https://imgur.com/nstL9Aq
You’re using a promise like a observable. A promise can only pass to the state settled (resolve or reject) only once. Can the promise leave the final state several times? No. Once it passes to the final state, there it will stay. It is a state machine which does not allow a step backwards from that final stage.
– Luiz Felipe