3

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 accomplish 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>
Clone
  • 3,378
  • 11
  • 25
  • 41
  • 2
    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](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript#Sending_form_data)) – Jonathan Lonowski May 15 '18 at 23:59

1 Answers1

2

You have 2 problems here:

  • I think you wanted to say await instead of wait ?
  • In submitForm, your resolve 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>
soywod
  • 4,377
  • 3
  • 26
  • 47