在 Javascript 中,异步等待是否等待所有嵌套函数完成?

the*_*oys 5 javascript async-await reactjs es6-promise

在下面的示例中,我需要在 fetch 方法中进行 fetchData 调用之前重置一些值。async await 在继续之前是否等待 reset 方法中的所有函数完成?

fetch = async () => {
  await this.reset();
  this.props.fetchData();
};

reset = () => {
  this.props.resetFilter();
  this.props.resetClient();
  this.props.resetUser();
};
Run Code Online (Sandbox Code Playgroud)

或者您必须执行以下操作?

fetch = () => {
  this.reset().then(() => {
    this.props.fetchData();
  });
};

reset = async () => {
  await this.props.resetFilter();
  await this.props.resetClient();
  await this.props.resetUser();
};
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

t.n*_*ese 7

async/await不会神奇地处理异步函数。它是一种语法添加,可让您更轻松地使用 Promise。

所以每当一个函数返回一个 Promise 时,你都需要显式地等待它。

await如果您想按顺序执行它们,请在每个前面写,如您在第二个示例中所示:

reset = async () => {
  await this.props.resetFilter();
  await this.props.resetClient();
  await this.props.resetUser();
};
Run Code Online (Sandbox Code Playgroud)

或者,如果您想允许那些异步函数交错Promise.all

reset = async () => {
  await Promise.all([
    this.props.resetFilter(),
    this.props.resetClient(),
    this.props.resetUser()
  ])
};
Run Code Online (Sandbox Code Playgroud)

如果您不像第一个示例中那样等待 Promises:

reset = () => {
  this.props.resetFilter();
  this.props.resetClient();
  this.props.resetUser();
};
Run Code Online (Sandbox Code Playgroud)

那么对于这三个调用,promise 链就被破坏了,这起初看起来可能不是问题,尤其是如果您假设它们总是会解决。但是如果这个承诺中的一个被拒绝,可能会导致未经处理的拒绝。