Tuesday, 20 February 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...