使用Promise

时间:2018-05-15 23:51:23

标签: javascript forms

我正在尝试编写可以按特定顺序执行以下操作的内容:(1)提交表单(2)print" Print me。" (3)等待3秒(4)打印"打印我。"

为什么我的代码没有完成此任务?



function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms));}
function submitForm() { return new Promise(resolve => document.getElementById('form').submit());}

async function test() {
    wait submitForm();
    console.log("Print me.")
    wait sleep(3000);
    console.log("Print me too.")
};

test();

<form id="form" type="hidden">
    <input value="" id="id" type="text">
    <input value="Submit" type="submit">
</form>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

这里有2个问题:

  • 我想你想说await而不是wait
  • submitForm中,您的resolve函数从未被调用,请参阅下面的更正

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

function submitForm() {
  return Promise.resolve(() => document.getElementById('form').submit())
}

async function test() {
    await submitForm();
    console.log("Print me.")

    await sleep(3000);
    console.log("Print me too.")
}

test()
<form id="form" type="hidden">
    <input value="" id="id" type="text">
    <input value="Submit" type="submit">
</form>