【发布时间】:2022-01-27 05:54:54
【问题描述】:
我研究了很多帖子、文章和文档。我正在寻求更深入的了解。
来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
await表达式导致async函数执行暂停,直到解决Promise,[...]
let fetchLocation = () => {
//fetches information from satellite system and
//returns a Vector2 of lat long on earth
return new Promise(resolve => {
setTimeout(() => {
resolve({
lat: 73,
long: -24
});
}, 2000);
});
}
//async functions automatically return a promise.
let main = async() => {
//awaits the promises resolution
let result = await fetchLocation();
console.log("I'm the awaited promise result", result)
//immediately returns a promise as promise pending
return result;
}
console.log(main().then(res => console.log("I'm the original promise, just passed along by the async function, it didn 't a-wait for me", res)))
在进入这个兔子洞之前,我知道 async/await 是让异步代码看起来同步的语法糖。
因此,我完全期望看到 main 返回 lat long 坐标。相反,它返回一个承诺。
几个问题。
-
MDN 文档有错吗?它实际上不会暂停执行吗?似乎 await 关键字实际上并没有“暂停”函数执行......调用 main 立即返回一个
Promise<pending>对象。然而,在它返回后,我们在等待的变量result中收到了已履行承诺的值。我想这来自事件循环? (并且异步返回语句仍然是同步的。) -
所以看起来 await 解包了一个 Promise,而 async 包装了一个 Promise,但是您需要在 async 中使用 await。我知道await实际上可能是引擎盖下的promise.then(),但是如果他们想让它在外观上完全同步,为什么不让async函数在与await一起使用时返回已解决的promise值?否则 async await 似乎有点多余。
【问题讨论】:
-
我不确定你到底在提议什么。您想知道为什么
async/await在不使用这些关键字的情况下的行为与同步代码不完全相同?如果不出意外,这将阻止调用者立即不使用await,这是一个非常常见的用例。await暂停执行,从“我是等待的承诺结果”日志之前的 2 秒延迟可以看出,但同步调用堆栈代码仍然运行并返回承诺。 Good video 这可能有助于解释为什么您会看到同步代码首先运行。 -
“因此,我完全希望看到 main 返回经纬度坐标。相反,它返回了一个承诺。”:
async函数 always 返回一个承诺。 -
我更想知道这个异步主函数如何显然同时是两件事。在 return 语句的情况下它可以是同步的,这意味着它没有等待。并且还以某种方式异步等待。我正在考虑解释器逐行读取函数。此外,我所提议的更像是不仅仅是在引擎盖下将 a then 链接到返回的 promise 对象,那么是什么让它变得更好?
标签: javascript asynchronous async-await