[英]What's the difference between using await keyword versus omitting it in an async function?
[英]What is the difference between using and omitting keyword “await” in these two code blocks?
我正在关注关于 async/await 的 MDN 文章,并且我了解在函数之前使用 async 关键字的目的,但我对 await 关键字有点困惑。 结果,我已经阅读了“等待”,并且我了解了一般概念,但是在涉及示例时我仍然不确定。 例如,这是一段使用 async/await 的简单代码(如 MDN 文章中所示)。
async function hello() {
return greeting = await Promise.resolve("Hello");
};
hello().then(value => console.log(value));
如您所料,这会将“Hello”记录到控制台。 但即使我们省略“await”,它也具有完全相同的 output。
async function hello() {
return greeting = Promise.resolve("Hello"); // without await
};
hello().then(value => console.log(value));
有人可以帮我准确理解 Promise.resolve 之前的 await 关键字在做什么吗? 为什么output即使省略也一样? 谢谢。
在最新的 JavaScript 引擎中,没有区别,只是因为return await somePromise
位于 function 代码的顶层。 如果它在控制块内(例如, try
/ catch
),那将很重要。
这是最近的变化。 在 ES2020 之前, return await
版本会在流程中引入一个额外的异步“tick”。 但是,当正在await
的 promise 是本机 promise 时,这在 ES2020 的“规范更改”(而不是提议)中得到了优化。 (对于非本地 thenable,仍然存在小的差异。)
为免生疑问,两者之间有一个重要区别:
async function example() {
try {
return await somethingReturningAPromise();
} catch (e) {
// ...do something with the error/rejection...
}
}
和
async function example() {
try {
return somethingReturningAPromise();
} catch (e) {
// ...do something with the error/rejection...
}
}
在前者中,someReturningAPromise somethingReturningAPromise()
对 promise 的拒绝进入catch
块,因为它已被await
。 In the latter, it doesn't, because you've just returned the promise, which resolves the promise from the async
function to the promise somethingReturningAPromise()
returns, without subjecting it to the catch
.
但是在您的示例中,它不在任何控制结构中,此时await
在很大程度上是一种风格问题。
请记住, async
/ await
只是一个花哨的 API 用于处理 Promise。
async
function 始终隐式返回 promise(一旦到达第一个await
或return
语句)将在 function 代码本身最终到达其末尾时解决。 解析的 promise 值将等于函数的返回值。
async
允许您在异步 scope 内部使用await
。 Await 仅在 promise 之前才有意义(可能是另一个async
function 调用,一个 promise 使用new Promise()
就地创建等)。 不过,在非 promise 值之前使用await
不会造成任何伤害。
await
表示,就是这样,等待。 它告诉引擎在 scope 上“停止”代码执行,并在 promise 完成时恢复它。 await
然后会给您或“返回” promise 解析值。
只是给你一些实际的例子:
使用您的第一个代码:
async function hello() {
const greeting = await Promise.resolve("Hello"); // HERE I CAN USE await BECAUSE I'M INSIDE AN async SCOPE.
console.log('I will be printed after above promise is resolved.');
return greeting;
};
hello().then(value => console.log(value));
使用您的第二个代码,可以完全删除async
:
function hello() {
return Promise.resolve("Hello");
};
hello().then(value => console.log(value));
如果有任何疑问,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.