等待函数不适用于 jQuery 事件处理程序

Await function not working with jQuery event handler

我有一个 SweetAlert2 弹出窗口,用于验证用户上传的图片。在用户决定我需要 continue/stop 主函数后。

但它只是忽略了附加到 Swal 的 .then 函数。 因此,如果 img 具有良好的分辨率,它 returns true。否则它只是 returns false。即使弹出窗口显示。它已经 运行 剩下的主要功能代码。 img验证函数:

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

主要功能:

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

你把这个问题措辞得好像 SweetAlert2 没有尊重你的 then,但我认为实际上 jQuery 没有等待或尊重你的 return false;您在 async function 中发布它,而 jQuery 根本不知道如何在事件处理程序中等待 Promises。

您的函数传递给 on return 是一个 Promise,因为所有 async 函数 return 在所有情况下都是一个 Promise。您似乎希望 return false 取消可能提交表单的 #upload-it 按钮的默认行为,但是 JavaScript 事件处理程序不理解事件处理程序何时 return承诺,以及 jQuery doesn't either。这使得无法使用 return false 取消 async function 事件处理程序中的默认行为。

相反,请确保 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..
});