Asynchronous function - wait without waiting for a promise

I am trying to learn asynchronous wait. 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 like -

 Promise { <pending> } 

Instead of some meaning? Should the getResult() function wait for the myFun() function to solve its value?

+13
javascript asynchronous ecmascript-2017
source share
2 answers

If you use async / wait, all your calls should use Promises or async / wait. You cannot just magically obtain an asynchronous result from a synchronization call.

Your last call should be:

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

Or something like:

 (async () => console.log(await getResult()))() 
+10
source share

It makes no sense to asynchronize and wait when this is the actual case:

 Promise.resolve(3).then(console.log); console.log(4); 4 3 

In other words, since then () branches and runs slower than subsequent statements (even for the allowed Promise), we need to put subsequent statements in then, for example:

 Promise.resolve(3).then(_ => { console.log(_); console.log(4); }); 3 4 

And since this is true, then why wait. So I still have to understand why asynchronous and pending generally exist.

0
source share

All Articles