Home > Net >  should I use `await` when calling an `async` function inside another `async` function?
should I use `await` when calling an `async` function inside another `async` function?

Time:03-01

I have an async function which calls another async function:

const func1 = async () => {...}

const func2 = async () => {func1()}

I wonder does it still make sense or unnecessary at all to use await to call func1() inside func2 ? :

const func2 = async () => {await func1()} // is the `await` better or unnecessary at all?

CodePudding user response:

Generally, the correct thing to do is await the nested function.

If you do not await the func1, it executes in a "fire and forget" mode, so you can't tell if it failed or not, and any lines of code below it in func2 may execute before func1 completes.

The only time it makes a lot of sense to not await is if you want to return a promise from your function.

Ex:

const func2 = async () => { return func1(); }

await func2();

When you return the promise, then that promise is awaited if you use await when calling func2

  • Related