Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  137] [ 6]  / answers: 1 / hits: 129766  / 7 Years ago, fri, august 25, 2017, 12:00:00

I'm trying to learn async-await. In this code -



const myFun = () => {
let state = false;

setTimeout(() => {state = true}, 2000);

return new Promise((resolve, reject) => {
setTimeout(() => {
if(state) {
resolve('State is true');
} else {
reject('State is false');
}
}, 3000);
});
}

const getResult = async () => {
return await myFun();
}

console.log(getResult());


why am I getting output as -



Promise { <pending> }


Instead of some value? Shouldn't the getResult() function wait for myFun() function resolve it's promise value?


More From » node.js

 Answers
69

If you're using async/await, all your calls have to use Promises or async/await. You can't just magically get an async result from a sync call.



Your final call needs to be:



getResult().then(response => console.log(response));


Or something like:



(async () => console.log(await getResult()))()

[#56660] Tuesday, August 22, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reecep

Total Points: 141
Total Questions: 95
Total Answers: 113

Location: Finland
Member since Mon, Nov 8, 2021
3 Years ago
;