为什么需要使用await关键字来调用异步方法
const tryToGetResult = async () => {
const networkResult = await someNetworkRequest();
console.log(networkResult); //Make sure networkResult is resolved to an object
return networkResult;
}
const result = tryToGetResult();
networkResult
已经是一个对象,并且已经使用async/await
处理了该流程.但是我不明白为什么const result = tryToGetResult()
(这里的result
变量)得到的是promise
呢?
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?
我知道可以通过将await
添加为const result = await tryToGetResult();
来解决这种情况,我根本不明白为什么在这里需要await
可以清楚地证明执行流程正确吗?
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?
标记为异步的函数始终返回Promise
Functions marked as async always return a Promise
来自 https://developer.mozilla. org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function
异步函数是通过事件循环异步操作的函数,该事件使用隐式Promise返回其结果.
An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result.