I am trying to write something that could do the following in that particular order: (1) submit a form (2) print "Print me." (3) wait 3 seconds (4) print "Print me too."
Why doesn't my code acplish this?
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>
I am trying to write something that could do the following in that particular order: (1) submit a form (2) print "Print me." (3) wait 3 seconds (4) print "Print me too."
Why doesn't my code acplish this?
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>
Share
Improve this question
asked May 15, 2018 at 23:51
CloneClone
3,66811 gold badges30 silver badges49 bronze badges
2
- 3 JavaScript can't run through a form submission. That causes the browser to navigate to a new page (or at least a new copy of the page), which interrupts and unloads all of the scripts. – Consider using Ajax to "submit" the form in the background (ref: MDN - Sending form data) – Jonathan Lonowski Commented May 15, 2018 at 23:59
- Sure it can. A form submit can return a file download. So the page can still be there. – Paul Commented Nov 2, 2023 at 16:24
1 Answer
Reset to default 2You have 2 problems here:
- I think you wanted to say
await
instead ofwait
? - In
submitForm
, yourresolve
function was never called, see my correction below
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>