0

I'm mad about this: Looking for validation of some fields via AJAX, inputs «identificacion», «usuario» and «correo» can't be duplicated in database.

The function:

async function duplicado(campo) {
    let URLscript =      window.location.protocol+"//"+window.location.hostname+document.getElementById("ruta_relativa").value;
    let opciones = {
        method: 'POST',
        body: "campo="+campo.name+"&valor="+campo.value,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    };
    let peticion = await fetch(URLscript+"comprobar_duplicados.php",opciones);
    let respuesta = await peticion.json();
    console.log(respuesta.duplicado);
    return respuesta.duplicado;
}

document.addEventListener("change", function(evento) {
    if ((evento.target.id == "identificacion") || (evento.target.id == "usuario") || (evento.target.id == "correo")) {  
        console.log(duplicado(evento.target));
        if (duplicado(evento.target)) {
            alert("Error... duplicated");
            evento.target.focus();
        }
    }
});

Inside function, console logs the right value and I try to return it. Outside function -before it needed- console logs something like this:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: <true|false>

How can I get PromiseResult value and use it in a expression? Thanks a lot.

PD: My apoligize: First time in StackOverflow.

  • 2
    You are not `await`ing the result of `duplicado(campo)`. `if (await duplicado(evento.target))` – Ruan Mendes Sep 07 '21 at 19:37
  • You to use the await keyword when calling the duplicado async function. Then you will have your result outside of the function. – tomerpacific Sep 07 '21 at 19:37
  • 1
    Unrelated tip: Not sure why you have a `catch` block that does nothing but re-throw the exception. Get rid of that block! – Ruan Mendes Sep 07 '21 at 19:40
  • Agree with the comments. Also note that the fetch ought to go into the try. More advanced note that the whole duplicate check should be debounced. (Less seriously, this post is well titled. See https://en.wikipedia.org/wiki/Promises,_Promises_(musical)) – danh Sep 07 '21 at 19:41
  • First of all, thanks a lot :) I've tried to put await as you comment, but there's something worng with it. Reading docs, keyword «await» seems to be used inside an async function: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/await As your comments says, I've removed and simplify the function (I'm sorry: lot of attemps leave toons of garbage). Ah, haha, Danh! Now, should I seek the musical and watch it while i'm crying about my mess code :`) – David De La Sierra-Llamazares Sep 07 '21 at 21:07

0 Answers0