JS 异步/等待 - 为什么等待需要异步? [英] JS async/await - why does await need async?
问题描述
为什么使用 await
需要声明它的外部函数 async
?
Why does using await
need its outer function to be declared async
?
例如,为什么这个 mongoose 语句需要它所在的函数来返回一个 promise?
For example, why does this mongoose statement need the function it's in to return a promise?
async function middleware(hostname, done) {
try {
let team = await Teams.findOne({ hostnames: hostname.toLowerCase() }).exec();
done(null, team);
} catch (err) { done(err); }
}
我看到运行时/转译器将 Teams 承诺解析为它的价值,并发出异步信号,它抛出"拒绝的承诺.
I see the runtime/transpiler resolving the Teams promise to it's value and async signaling it "throws" rejected promises.
但是 try/catch 捕获"了那些被拒绝的 promise,那么为什么 async 和 await 如此紧密地耦合在一起呢?
But try/catch "catches" those rejected promises, so why are async and await so tightly coupled?
推荐答案
我不了解 JavaScript 语言设计的讨论,但我认为这是出于相同的原因 C# 语言 需要 async
(另见 我的博客).
I'm not privy to the JavaScript language design discussions, but I assume it's for the same reasons that the C# language requires async
(also see my blog).
即:
- 向后兼容.如果
await
突然成为一个新关键字,那么任何使用await
作为变量名的现有代码都会中断.由于await
是上下文关键字(由async
激活),只有 打算 使用await
作为关键字的代码将await
作为关键字. - 更容易解析.
async
让转译器、浏览器、工具和人类更容易解析异步代码.
- Backwards compatibility. If
await
was suddenly a new keyword everywhere, then any existing code usingawait
as a variable name would break. Sinceawait
is a contextual keyword (activated byasync
), only code that intends to useawait
as a keyword will haveawait
be a keyword. - Easier to parse.
async
makes asynchronous code easier to parse for transpilers, browsers, tools, and humans.
这篇关于JS 异步/等待 - 为什么等待需要异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!