Exter
Exter

Reputation: 689

Does Javascript finish executing async function even after the rest of the code has finished executing?

This is what I tried -

async func1(){
 // do asynchronous calls with await
 console.log("call finished");
}

func2(){
 func1(); // without await
 console.log("func2 finished");
 return;
}

func2();

The output was - func2 finished call finished. So even after the parent function completed execution, the async function still completed what it was intended for.

Will this work in case of an API where we are returning something to an external service? Like cloud functions -

async func1(){
 // do asynchronous calls - post db using await
 console.log("call finished");
}

func2(){
 func1(); // without await
 return response.status(200).send("");
}

func2();

Will the database call complete even if the response.send is executed first provided I don't await for the first function to finish execution?

Upvotes: 1

Views: 1231

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370759

Yes, the Promise returned by an async function is only a handle that lets you chain logic onto the asynchronous value or timing provided by the function. You don't have to do anything with it. If you don't use .then or await to chain off of it, the async function still runs and goes through all its code - it's just that the Promise it returns doesn't get used elsewhere.

That said, dangling promises are usually a bad idea - in most cases, you probably should chain a .then or .catch onto a promise.

Upvotes: 1

Related Questions