async function - await not waiting for promise

Javascriptnode.jsAsynchronousEcmascript 2017

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

What you need to understand is that async/await does not make your code run synchronously, but let's you write it as if it is:

In short: The function with async in front of it is literally executed asynchronously, hence the keyword "async". And the "await" keyword wil make that line that uses it inside this async function wait for a promise during its execution. So although the line waits, the whole function is still run asynchronously, unless the caller of that function also 'awaits'...

More elaborately explained: When you put async in front of a function, what is actually does is make it return a promise with whatever that function returns inside it. The function runs asynchronously and when the return statement is executed the promise resolves the returning value.

Meaning, in your code:

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

The function "getResult()" will return a Promise which will resolve once it has finished executing. So the lines inside the getResult() function are run asynchronously, unless you tell the function calling getResult() to 'await' for it as well. Inside the getResult() function you may say it must await the result, which makes the execution of getResult() wait for it to resolve the promise, but the caller of getResult() will not wait unless you also tell the caller to 'await'.

So a solution would be calling either:

getResult().then(result=>{console.log(result)})

Or when using in another function you can simply use 'await' again

async callingFunction(){
    console.log(await(getResult());
}

Solution 3 - Javascript

This is my routine dealing with await and async using a Promise with resolve and reject mechanism

    // step 1 create a promise inside a function
	function longwork()
	{
		p =  new Promise(function (resolve, reject) {
			result = 1111111111111 // long work here ; 
			
			if(result == "good"){
				resolve(result);
			}
			else
			{
				reject("error ...etc")
			} 
		})

		return p
	}
    
    // step 2 call that function inside an async function (I call it main)and use await before it
	async function main()
	{
         final_result = await longwork();
         //..

	}  

    //step 3 call the async function that calls the long work function
	main().catch((error)=>{console.log(error);})
	
	

Hope that saves someone valuable hours

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhg_gitView Question on Stackoverflow
Solution 1 - JavascriptBen FortuneView Answer on Stackoverflow
Solution 2 - JavascriptPim_nr_47View Answer on Stackoverflow
Solution 3 - JavascriptNassimView Answer on Stackoverflow