Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
Await function not working with jQuery event handler

I have a SweetAlert2 popup that's verifying images uploaded by users. After the user decides I need to continue/stop the main function.

But it just ignores the .then function appended to Swal. So if the img have good resolution, it returns true. And else it just returns false. Even if the popup shows. It already ran the rest of the main function code. Img verify function:

function verifyimage(imgurl) {
  return new Promise((resolve) => {
    var tmpImg = new Image();
    tmpImg.src = imgurl;
    $(tmpImg).on("load", function () {
      var orgWidth = tmpImg.width; //w
      var orgHeight = tmpImg.height; //h
      if (orgHeight <= 720 || orgWidth <= 1500) {
        Swal.fire({
          position: "center",
          icon: "error",
          title: `title`,
          showConfirmButton: true,
          showCancelButton: true
        }).then((result) => {
          if (result.isConfirmed) {
            resolve(true); //img ok
          } else {
            resolve(false); //dont upload
          }
        });
      } else {
        resolve(true); //upload, good resolution
      }
    });
  });
}

Main function:

$(document).on("click", "#upload-it", async function() {
  var valueimg = geturl();
  var imgvefify = await verifyimage(valueimg);
  if (!imgvefify) {
    console.log("nope, invalid img");
    return false;
  }
//upload to server etc..
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You've phrased this question as if SweetAlert2 is not respecting your then, but I think it's actually the case that jQuery is not waiting for or respecting your return false; you're issuing it in an async function and jQuery simply doesn't know how to await Promises in event handlers.

Your function passed to on returns a Promise, because all async functions return a Promise in all cases. It seems like you want the return false to cancel the default behavior of the #upload-it button that presumably submits a form, but JavaScript event handlers don't understand when event handlers return Promises, and jQuery doesn't either. This makes it impossible to use return false to cancel the default behavior in an async function event handler.

Instead, make sure to immediately prevent the default behavior and stop propagation before awaiting anything, which you can do by calling methods on the event object. Having prevented the default behavior, you won't be able to "continue" it once the async function completes, but you can still programmatically submit the form.

$(document).on("click", "#upload-it", async function(event) {
  event.preventDefault();
  event.stopPropagation();

  // validate the form
  // upload to server etc..
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda