1

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Parth Kapadia
  • 507
  • 6
  • 18

1 Answers1

1

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • So in this case, the API will return a response first and after that `func1` will post data to the database? – Parth Kapadia Jul 01 '22 at 04:53
  • 1
    Yes, the `return response.status(200).send("")` will return the response to the client, and then once whatever async action inside `func1` finishes, it'll then log `call finished` – CertainPerformance Jul 01 '22 at 04:54
  • 3
    With services such as Cloud Functions, Cloud Run, etc. CPU processing ends when the response is returned. The CPU can be idled to zero, which means unhandled promises might not complete. – John Hanley Jul 01 '22 at 04:58
  • For anyone figuring this out for services such as Google Cloud Functions, this might help - https://stackoverflow.com/q/49746980/10217754. – Parth Kapadia Jul 01 '22 at 05:56