javascript async await 使用 Promise 提交带有 onsubmit 的表单

javascript async await Submitting a form with onsubmit using Promise

我有以下代码。

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript">
      function sleep( lf_ms ) {
        return new Promise( resolve => setTimeout( resolve, lf_ms ) );
      }

      async function check_form() {
        alert( 'Test 1' );
        await sleep( 1000 );
        alert( 'Test 2' );

        return false;
      }
    </script>
  </head>
  <body>
    <form name="myform" method="post" action="test.htm" onsubmit="return check_form();">
      <input type="text" name="city"><br>
      <br>
      <a href="javascript:check_form();">check the method call via link</a><br>
      <br>
      <button type="submit">check the method call via submit button</button><br>
      <br>
    </form>
  </body>
</html>

我想休眠函数 check_form() 1 秒。

如果我点击link,将显示"Test 1"和"Test 2"。如果我单击提交按钮,只会显示 "Test 1"。我在这里做错了什么?

我的问题与不同。因为没有使用 javascript 事件处理程序 onsubmit。

return check_form() 并不像您想象的那样 return falseAsync functions always return an implicit Promise 因此,您的表单仍处于提交状态。第一个 alert 出现是因为到那时它仍然是同步的。 sleep 之后的所有内容都将安排在稍后的时间,表单提交将不会等待。

要解决它,您可以调用该函数,然后 然后 return false.

function sleep(lf_ms) {
  return new Promise(resolve => setTimeout(resolve, lf_ms));
}

async function check_form() {
  console.log('Test 1');
  await sleep(1000);
  console.log('Test 2');
}
<form name="myform" method="post" onsubmit="check_form(); return false;">
  <input type="text" name="city"><br>
  <br>
  <a href="javascript:check_form();">check the method call via link</a><br>
  <br>
  <button type="submit">check the method call via submit button</button><br>
  <br>
</form>


编辑地址

User input is checked in the function check_form. If the inputs are error-free, the function returns true. If there are errors, the function returns false. In the event of an error, the page that is stored in the attribute action of the tag form should not be called.

你不能像这样暂停JavaScript,但你可以使用return false停止提交,然后在你验证之后,通过JavaScript提交表单。

function sleep(lf_ms) {
  return new Promise(resolve => setTimeout(resolve, lf_ms));
}

async function check_form(form) {
  console.log('Test 1');
  await sleep(1000);
  console.log('Test 2');

  let city = document.getElementById('city').value;
  // Validation
  if (form !== undefined && city.trim() !== "") {
    // Validation succeeded, submit the form
    form.submit();
  }
}
<form name="myform" method="post" onsubmit="check_form(this); return false;">
  <input type="text" id="city" name="city"><br>
  <br>
  <a href="javascript:check_form();">check the method call via link</a><br>
  <br>
  <button type="submit">check the method call via submit button</button><br>
  <br>
</form>