Await函数无法与jQuery事件处理程序一起使用



我有一个SweetAlert2弹出窗口,用于验证用户上传的图像。在用户决定我需要继续/停止主功能之后。

但它只是忽略了附加在Swal后面的.then函数。因此,如果img具有良好的分辨率,则将返回true。否则,它只是返回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的函数返回Promise,因为所有async函数在任何情况下都返回Promise。您似乎希望return false取消#upload-it按钮的默认行为,该按钮可能会提交表单,但JavaScript事件处理程序不知道事件处理程序何时返回Promises,jQuery也不知道。这使得无法使用return false来取消async function事件处理程序中的默认行为。

相反,请确保在等待任何事情之前立即阻止默认行为并停止传播,这可以通过调用事件对象上的方法来实现。在阻止了默认行为之后,您将无法"继续";一旦async function完成,但您仍然可以通过程序提交表单。

$(document).on("click", "#upload-it", async function(event) {
event.preventDefault();
event.stopPropagation();
// validate the form
// upload to server etc..
});

最新更新