javascript 在 then 块中提交表单并使用 swal 从非异步函数中 return false

javascript submit form in then block and return false from a non-async function using swal

我正在尝试使用 onsubmit return myFunc() 提交表单,但我也想在函数内部使用 swall。这是我的代码的样子。 <form action="./script.php" onsubmit"return myFunc()"> </form>

let userName = $("#userName")
// use some validation here and finally

swal({
     title: "Are you sure",
     text: "Some Text"
     buttons: ['No', 'Yes']
     }).then((result) { 
         if(result) {
              console.log("Here we are!! ")
              return true
             // This is when I want the form to be submitted other wise return false
         } else {return false}        
    })
return false;
}    

发生的事情是函数 return false 并且永远不会执行 .then 块中的代码。

代码中存在一些语法错误。 function 关键字或 =>then 参数中丢失,并且在 swal() 的参数列表中缺少一个逗号。除此之外,混合同步和异步任务时逻辑不起作用。

实际的事件侦听器是 onsubmit 属性的内容,它调用 myFunc 和 returns 从该函数返回到内部事件处理程序的值。 swal() 调用 returns 一个承诺,然后在传递给 then 的回调函数中进行处理。 swal 调用是异步的,回调函数是在用户真正点击了警告框中的按钮后执行的。那时,myFunc已经完成返回false

要解决此问题,您必须在所有情况下阻止表单提交的默认操作,如果 swal 结果为“是”,则在传递给 then。像这样:

const form = document.querySelector('#form');

function myFunc(e) {
  e.preventDefault(); // Prevent the form submission in any case
  swal({
    title: "Are you sure",
    text: "Some Text",
    buttons: ['No', 'Yes']
  }).then((result) => {
    if (result) {
      console.log('Submit the form.')
      // form.submit(); // Uncomment this line to submit the form     
    } else {
      console.log('No submission.')
    }
  });
}

form.addEventListener('submit', myFunc);
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
<form id="form">
  <input type="submit" value="Submit">
</form>