“async/await”链中的所有函数都必须使用“async/await”关键字吗?

GN.*_*GN. 4 javascript async-await

链中的所有函数都async/await必须使用async/await关键字吗?

async function one() {
  return await fetch(.....);
}

async function two() {
  return await one();
}

async function three() {
  return await two();
}
Run Code Online (Sandbox Code Playgroud)

我在教程中看到了一些示例,其中调用者不必使用关键字。

Cer*_*nce 6

不,至少在这个例子中不是 - 如果你有一个函数只是awaiting 一个 Promise 并returning 结果,你可以只返回该 Promise ,而不需要任何asyncor await

function one() {
  return fetch(.....);
}

function two() {
  return one();
}

function three() {
  return two();
}
Run Code Online (Sandbox Code Playgroud)

如果您想要一个扁平的函数体,则需要await在该函数消耗Promise 并需要在将另一个已解析的 Promise 返回给调用者之前执行其他操作时使用。例如:

async function one() {
  const fetchResult = await fetch(.....);
  // do something with fetchResult
  return foo;
}

function two() {
  return one();
}

function three() {
  return two();
}
Run Code Online (Sandbox Code Playgroud)

这里,oneawaitingfetch调用,然后在返回 Promise 之前对其执行一些操作,但是two不需three要这样做async,因为它们只是调用一个返回 Promise 的函数并将该 Promise 返回给调用者。如果two或者three还必须在等待之后但在解决之前做一些事情,那么他们将不得不使用await(如果你想要一个扁平的函数体):

async function one() {
  const fetchResult = await fetch(.....);
  // do something with fetchResult
  return foo;
}

async function two() {
  const oneResult = await one();
  console.log('got result for one');
  return oneResult;
}

function three() {
  return two();
}
Run Code Online (Sandbox Code Playgroud)