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
:
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);
})()
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:
let value = await validateForm();
Post a Comment for "How To Get The Return Value Of A Javascript Promise?"