Home > database >  Await function not working with jQuery event handler
Await function not working with jQuery event handler

Time:02-26

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..
});

CodePudding user response:

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..
});
  • Related