Install ExtensionApp Store

Ok, Sometimes Async Await

Ok, Sometimes Async-Await
好的,有时异步等待

Normally, I continue believing that the classic (well, ES6) promise.then().catch().finally() is nicer than using the newer ES17 async-await syntax, because of function composability1. There are 2 cases where I think async-await is neater, and one where it may perceivably come in handy:
通常,我仍然相信经典(嗯,ES6) promise.then().catch().finally() 比使用较新的 ES17 async-await 语法更好,因为函数可组合性 1 。我认为 async-await 在两种情况下更简洁,其中一种情况可能会派上用场:

1. Early Return/Throwing Errors
1. 提前返回/投掷错误

async function returnEarly(): Promise<SomeType | undefined> {
  if (someCondition) return;
  await networkRequest();
  if (someOtherCondition) return;
  return await someOtherNetworkRequest();
}

This way, your function can return early concisely, but still always return a Promise. This is because, all values returned from an async function are automatically wrapped in a Promise if they aren't already. The equivalent code is pretty ugly:
这样,您的函数可以简洁地提前返回,但仍然始终返回 Promise 。这是因为,从 async function 返回的所有值都会自动包装在 Promise 中(如果尚未包装)。等效代码非常难看:

function returnEarly(): Promise<SomeType | undefined> {
  if (someCondition) return Promise.resolve();
  return networkRequest().then(() => {
    if (someOtherCondition) return Promise.resolve();
    return someOtherNetworkRequest();
  });
}

2. Promise Drilling 2.无极钻探

async function hotPotato() {
  const a = await networkRequestA();
  const b = await networkRequestB(a);
  return await networkRequestC(a, b);
}

Sometimes, a computation requires a value several promises upstream. Using async-await, you see the entire function's scope trivially, so you don't need to drill down with the value.
有时,计算需要上游多个承诺的值。使用 async-await ,您可以轻松地看到整个函数的范围,因此您不需要深入了解该值。

The equivalent code is ugly:
等效代码很丑陋:

function hotPotato() {
  return A()
    .then((a) => B(a).then((b) => [a, b]))
    .then(([a, b]) => C(a, b));
}

3? [object AsyncFunction]
3? [对象异步函数]

This does not generally strike me as useful, but can theoretically come in handy.
我通常觉得这没什么用,但理论上可以派上用场。

Object.prototype.toString.call(async () => producePromise()); // '[object AsyncFunction]'
Object.prototype.toString.call(() => producePromise()); // '[object Function]'

So the language gives us a way to know if a function was declared with the async modifier. In some contrived scenario, we can imagine that it may be very useful to be able to check during runtime if the function will be asynchronous before invoking it.
因此,该语言为我们提供了一种方法来了解函数是否是使用 async 修饰符声明的。在某些人为的场景中,我们可以想象,能够在运行时检查函数在调用之前是否是异步的可能非常有用。


Footnotes 脚注

  1. Composability: fetchThing().then(doThing).catch(logError).finally(toFalse) ↩可组合性: fetchThing().then(doThing).catch(logError).finally(toFalse) ↩