Skip to content Skip to sidebar Skip to footer

Js Ajax: Promise Dependant Submit Always Submitted

Finally, I managed to do this: On the onsubmit event, async function check_submit() is called. validar(...) function returns a promise (I guess), and with .then() and .catch() y h

Solution 1:

Explaining with an example suppose I have a form that I validate using promised based approach. Suppose validar() is a function that does some validation and takes 3 secs (I have many fields you know!). But when used like this it fails! see in below comments as to why is so.

<formaction="google.com"id="frm"><inputid="txt"><buttontype="submit">submit</button></form><script>document.getElementById('frm').onsubmit = () => {
    var check = check_submit();
    console.log(check); //Promise {<pending>}console.log(check ? true : false) // which is evaluates to true! (check ? true : false) <-- true//So browser proceeds with form's default behavior which is to submit on google.com
  }

  functionvalidar() {
    returnnewPromise(function(resolve, reject) {
      setTimeout(() =>resolve(false), 3000)
    });
  }

  asyncfunctioncheck_submit() {
    var result = validar(); // <-- this line NEVER WAITS for the promise of validar to get resolve() 'ed // instead its current value which is Promise {<pending>}  is used immediatly and RETURNED!return result;
  }
</script>

How to make it work then? It's simple just stop the default behavior by returning false in onsubmitunconditionally and manually submit form(if valid) when the promise value gets resolved

<formaction="google.com"id="frm"><inputid="txt"><buttontype="submit">submit</button></form><script>document.getElementById('frm').onsubmit = () => {
    check_submit(); //<-- will handle our form submission businessreturnfalse; //unconditional
  }

  functionvalidar() {
    returnnewPromise(function(resolve, reject) {
      setTimeout(() =>resolve(false), 3000)
    });
  }

  asyncfunctioncheck_submit() {
    var result = awaitvalidar(); //<-- this line NOW WAITS (due to await) for the promise of validar to get resolve() 'edif (result) {
      alert('submitting form as validar returned true')
      document.getElementById('frm').submit(); // submit manully as promise'd value returned true
    } elsealert('meh')
  }
</script>

Post a Comment for "Js Ajax: Promise Dependant Submit Always Submitted"