Skip to content Skip to sidebar Skip to footer

How To Get The Return Value Of A Javascript Promise?

I am struggling to understand how to get the value of a promise within Javascript to be able to check whether it is true or false. let valid = validateForm(); if ( valid === true

Solution 1:

You get it either with .then or await.

let valid = validateForm();

valid.then(function(valid) {
 if (valid) {

 }
})
async function submit () {
  const valid = await validateForm();

  if (valid) {

  }
}
``

Solution 2:

With the then or await:

functionpromiseExample  (){
    returnnewPromise((resolve, reject)=>resolve("hello world"))
}

(async ()  => {

    //with thenpromiseExample()
       .then(data =>console.log('with then: ', data))
       
    //with awaitvar data = awaitpromiseExample()
    console.log('with await: ', data);
})()

Solution 3:

It's hard to believe a simple google search didn't give you an answer for this but here goes:

validateForm().then(value => console.log(value))

or, within an async function:

letvalue = await validateForm();

Post a Comment for "How To Get The Return Value Of A Javascript Promise?"