最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Submitting a form with submit() using Promise - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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>

发布评论

评论列表(0)

  1. 暂无评论