Home > Enterprise >  Is the await keyword needed if I call an async function containing an await in its body without the
Is the await keyword needed if I call an async function containing an await in its body without the

Time:10-20

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.

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?

CodePudding user response:

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

CodePudding user response:

The await keyword tells the execution of your function to "await" foo2() before continuing. If you omit the await the code in foo2() will still run but foo1() will also continue on without making sure foo2() has completed. This is definitely allowed, just be careful because this can lead to race conditions.

  • Related