Isaac
Isaac

Reputation: 12874

Why the need of using await keyword for calling async method

const tryToGetResult = async () => {
  const networkResult = await someNetworkRequest();
  console.log(networkResult); //Make sure networkResult is resolved to an object
  return networkResult;
}

const result = tryToGetResult();

networkResult is already an object and the flow has been taken care of by using async/await. But I don't understand why const result = tryToGetResult(), the result variable here is getting a promise instead?

I understand that the situation can be fixed by adding await as const result = await tryToGetResult();, I simply don't understand why the need of await here coz the flow of execution is clearly correct?

Upvotes: 0

Views: 78

Answers (1)

Talha
Talha

Reputation: 817

Functions marked as async always return a Promise

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result.

Upvotes: 1

Related Questions