Reputation: 7852
I am aware of the questions JavaScript wait for asynchronous function in if statement [duplicate] and How do I return the response from an asynchronous call?, but (maybe because I am an absolute JS beginner) I am not able to implement those ideas.
Using async await documentation, I can make this example work:
let hello = async () => { return "Hello" };
hello().then((value) => console.log(value))
It just outputs Hello
. However, I would like my code to check what the function hello
returns at some later point. Something like this:
if ( /* what comes here? */) {
console.log("Hello was said")
}
How could I do this? How to formulate this if statement to check if hello
indeed returned "Hello"?
Upvotes: 0
Views: 1576
Reputation: 11
Here is an example that may clear up some of the fog.
"
let waitOver = false;
let whatToDo = setFree("Jill",5);
console.log(whatToDo);
let theWait = setInterval( () => {
waitOver ? clearInterval(theWait) :
console.log(" and .. wait");
}, 1000);
function gone(secs) {
return new Promise(resolve => setTimeout(resolve, secs*1000));
}
function setFree(someone,secs) {
console.log(`If you truly love ${someone}, set ${someone} free`);
gone(secs).then(() => {
console.log(`Back! ${someone} is yours`);
waitOver = true;
return `${someone} is yours`;
}).catch(`Hunting ${someone} down and kill ${someone}`);
return " Here you wait ... ";
}
This is what you'll get:
If you truly love Jill, set Jill free
Here I wait ...
and .. wait
and .. wait
and .. wait
and .. wait
Back! Jill is yours*
NOTICE ALSO that after calling setFree(), any check on waitOver in the main execution thread would be false unless that check is made after gone() has been handled by its .then() handler.
If there is no .then() handler then gone() would have gone to the woods, and you will never know if Jill ever came back, even if she did because that completion was never handled :-)
Upvotes: 1
Reputation: 12036
hello().then((value) => ...)
basically means that if the promise (await) is fulfilled, it should call a function(value = <return_value>){}
... so...
hello().then((value) => {
if(value == 'Hello'){
console.log("Hello was said");
}
});
Upvotes: 1
Reputation: 128
The if statement can be wrapped in an async function like this:
let hello = async () => { return "Hello" };
async function foobar() {
if(await hello() == 'Hello')
console.log('yay')
}
foobar()
await
can only be used in async functions.
Promises continue giving you promises as a return, but await can evaluate a Promise in an async function.
Upvotes: 0
Reputation: 1223
It depend on what you mean for "Later".
Upvotes: 0