Tuesday, February 20, 2018

javascript - async function - await not waiting for promise



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


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


Answer



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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...