JS async / await - 为什么等待需要异步? [英] JS async/await - why does await need async?
问题描述
为什么使用 await
需要将其外部函数声明为 async
?
Why does using await
need it's 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); }
}
我看到运行时/转发器解析了团队对它的价值和异步的承诺发信号它抛出被拒绝的承诺。
I see the runtime/transpiler resolving the Teams promise to it's value and async signaling it "throws" rejected promises.
但是try / catch捕获那些被拒绝的承诺,为什么异步并等待如此紧密耦合?
But try/catch "catches" those rejected promises, so why are async and await so tightly coupled?
推荐答案
从 https://stackoverflow.com/a复制/ @70044179 / 1483977 @phaux:
这些答案都给出了为什么async关键字为$ b $的有效参数好的,但他们都没有提到为什么将
添加到规范中的真正原因。
These answers all give valid arguments for why the async keyword is a good thing, but none of them actually mentions the real reason why it had to be added to the spec.
原因是这是一个有效的JS pre-ES7
The reason is that this was a valid JS pre-ES7
function await(x) {
return 'awaiting ' + x
}
function foo() {
return(await(42))
}
根据你的逻辑, foo()
返回承诺{42}
或
等待42
? (返回Promise将向后突破
兼容性)
According to your logic, would foo()
return Promise{42}
or
"awaiting 42"
? (returning a Promise would break backward
compatibility)
所以答案是: await
是一个常规的标识符和它只是
在异步函数中被视为关键字,所以它们必须以某种方式标记为
。
So the answer is: await
is a regular identifier and it's only
treated as a keyword inside async functions, so they have to be marked
in some way.
有趣的事实:原始spec为异步语法提出了更轻量级的函数^ foo()
。
{}
Fun fact: the original spec proposed more lightweight function^ foo()
{}
for async syntax.
这篇关于JS async / await - 为什么等待需要异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!