首页 > 解决方案 > 承诺并提交

问题描述

我正在构建一个带有前端密码散列的表单:

<form action='login.php' method='post' onsubmit='hash(this)'>
    Password: <input type='password' name='password'><br>
    <input type='hidden' name='shapassword'>
    <input type='submit'>
</form>

我的哈希函数使用 SubtleCrypto Web API。它调用digest()函数,该函数返回一个 Promise:

function hash(form) {
    const buff = new TextEncoder().encode(form.password.value);
    p1 = crypto.subtle.digest('SHA-512', buff).then(param => {
        form.shapassword.value = new TextDecoder().decode(param);
    });
}

但是,shapassword 不会传递给从表单接收数据的脚本。我想hash()在 Promise 完成之前返回,对吗?如何防止离开hash()函数或从函数访问form对象then

标签: javascriptscopepromisees6-promise

解决方案


您应该调用preventDefault以防止用户单击提交表单,并在实际提交表单之前等待Promise解决。使用 Javascript 而不是内联处理程序附加侦听器也是一种好习惯:

const form = document.querySelector('form');
form.addEventListener('submit', (e) => {
  e.preventDefault();
  getEncodedText(form);
});

function do(form) {
  const buff = new TextEncoder().encode(form.password.value);
  crypto.subtle.digest('SHA-512', buff).then(param => {
    form.shapassword.value = new TextDecoder().decode(param);
    form.submit();
  });
}

推荐阅读