-4

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 ) {
}

If I console.log the valid variable, it returns the following:

Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: true 

Within my if statement, I am trying to check whether the promise value is true, however I don't know how to gain access to this :/ Could anyone please advise how to check this?

Thanks

lky
  • 1,081
  • 3
  • 15
  • 31

3 Answers3

2

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) {

  }
}
``

blockhead
  • 9,655
  • 3
  • 43
  • 69
2

With the then or await:

function promiseExample  (){
    return new Promise((resolve, reject)=> resolve("hello world"))
}

(async ()  => {

    //with then
    promiseExample()
       .then(data => console.log('with then: ', data))
       
    //with await
    var data = await promiseExample()
    console.log('with await: ', data);
})()
Ziv Ben-Or
  • 1,149
  • 6
  • 15
0

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:

let value = await validateForm();
Smytt
  • 364
  • 1
  • 11