JS 异步/等待 - 为什么等待需要异步? [英] JS async/await - why does await need async?

查看:34
本文介绍了JS 异步/等待 - 为什么等待需要异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么使用 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).

即:

  1. 向后兼容.如果 await 突然成为一个新关键字,那么任何使用 await 作为变量名的现有代码都会中断.由于 await 是上下文关键字(由 async 激活),只有 打算 使用 await 作为关键字的代码将 await 作为关键字.
  2. 更容易解析.async 让转译器、浏览器、工具和人类更容易解析异步代码.
  1. Backwards compatibility. If await was suddenly a new keyword everywhere, then any existing code using await as a variable name would break. Since await is a contextual keyword (activated by async), only code that intends to use await as a keyword will have await be a keyword.
  2. Easier to parse. async makes asynchronous code easier to parse for transpilers, browsers, tools, and humans.

这篇关于JS 异步/等待 - 为什么等待需要异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆