0

can you help me with this code snippet? In this part, I make a ajax request to my c# controller only to validate a email and get the boolean value, but in the process, a promise returns status pending make a problem because i really need only the value inside the promise, here my code:

let Email = input;
let valida = ValidaEmail(Email);
console.log(valida);

The Function

async function ValidaEmail(email) {
    let promise = new Promise(resolve => {
        var string = JSON.stringify(email);
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/Home/EmailisValid", true);
        xhttp.setRequestHeader("Content-type", "application/json");
        xhttp.onreadystatechange = () => {
            if (xhttp.readyState === 4 && xhttp.status === 200)
                resolve(xhttp.response);
        };
        xhttp.send(string);
    });
    let retorno = await promise;
    console.log(retorno);
}

The Output: enter image description here

AnaBrando
  • 1
  • 1

1 Answers1

1

In the first you have to return result of promise from ValideEmail.

async function ValidaEmail(email) {
    let promise = new Promise(resolve => {
        var string = JSON.stringify(email);
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/Home/EmailisValid", true);
        xhttp.setRequestHeader("Content-type", "application/json");
        xhttp.onreadystatechange = () => {
            if (xhttp.readyState === 4 && xhttp.status === 200)
                resolve(xhttp.response);
        };
        xhttp.send(string);
    });
    let retorno = await promise;
    console.log(retorno);
    //////
    return retorno;
    //////
}

When you use ValidateEmail function you have to use await or .then();

let Email = input;
///
let valida = await ValidaEmail(Email);
console.log(valida);
// or
ValidaEmail(Email).then((valida) => {
   console.log(valida);
})

Andrey
  • 76
  • 2
  • Hi, sorry the delay , i was busy, anyway, i tried both ways in this way ValidaEmail(Email).then((valida) => { console.log(valida); }) - the promise always return pending and in let valida = await ValidaEmail(Email); in console show this error "Uncaught SyntaxError: await is only valid in async function" :( – – AnaBrando Feb 22 '20 at 17:19
  • Does your promise from request resolve? Put console log near with resolve(xhttp.response); – Andrey Feb 23 '20 at 10:37
  • yes resolve, in console show false or true, but the problem is the promise not waiting for sending the resolve value and return a promise pending :( by the logic, i try let valida = await ValidaEmail(Email); but the in console show this error "Uncaught SyntaxError: await is only valid in async function" – AnaBrando Feb 23 '20 at 13:32