Why the need of using await keyword for calling async method

一笑奈何 提交于 2019-12-23 04:58:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/55133876/why-the-need-of-using-await-keyword-for-calling-async-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!