Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is the await keyword needed if I call an async function containing an await in its body without the await keyword within another async function?

Step 1: I have function. This function has no return. Anyway I the async keyword to the function because I need to use an await inside this function.

Explanatory code example:

const foo1 = async () => {
    const a1 = await something... //For example findValueInDatabase()
}

Step 2:
I define another async function again using await inside its body. No return again.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Explanatory code example:

const foo2 = async () => {
    const a2 = await something... //For example sendEmail()
}

Step 2: Now I want to call the function defined in step 2 inside the function of stop one:

Explanatory code example:

const foo1 = async () => {
    const a1 = await something... //For example findValueInDatabase()

    foo2() //or await foo2()

    ...some more code to be executed...
}

Expections and questions regarding the behaviour of foo2 within foo1:

Do I need to add the await keyword to foo2 in order for it to be awaited? Does it make a difference? If so, what is the difference?

I would expect that the answer to that question is no.
foo2 will execute and in it a2 will be awaited which means that further code will not be executed until a2 is resolved. So await would not make any difference because calling foo2 within foo1 is like if the code of foo2 was directly in foo1.

Are my expectations wrong?

>Solution :

All async functions return a promise. If you care about the results of the promise, you can use await or the promise.then function. But if there’s no return and/or you don’t care about the return, you don’t need await/then

In foo1 you can use await on foo2 to ensure foo1 completes after foo2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading