我正在尝试编写可以按特定顺序执行以下操作的内容:(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;
答案 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>