avokevdo
avokevdo

Reputation: 119

If I define an async function and use await in the body, do I need to use await when calling the function?

an example:

async doSomething() {
  await asyncCall();
}

Do I need to use await when I call my doSomething function?

await doSomething();

or is this fine?

doSomething();

Upvotes: 9

Views: 2251

Answers (2)

toing_toing
toing_toing

Reputation: 2442

In your example, doSomething() returns a Promise. For you to return the data from an async function, you need to resolve or reject the promise.

When you do:

await doSomething();

doSomething() will wait for asyncCall() to be resolved.

When you do:

doSomething();

doSomething() will resolve asyncCall()in the background.

I think your confusion comes from the fact that await is only valid in async functions in javascript. If you want to run await doSomething() outside a async function, just wrap it around an anonymous async function like:

(async() => {
  await doSomething()
})();

Upvotes: 2

Nick
Nick

Reputation: 16576

It's important to understand that async/await is really just "sugar" on top of Promises. In other words, doSomething still returns a Promise (you can't use async await to get away from this fact!). So, to answer your question, you still need to use await (or chain a then call) to handle the eventual resolved or rejected Promise value.

Upvotes: 7

Related Questions