【问题标题】:In Javascript does async await wait for all nested functions to complete?在Javascript中异步等待是否等待所有嵌套函数完成?
【发布时间】:2019-03-15 14:46:19
【问题描述】:

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

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

reset = () => {
  this.props.resetFilter();
  this.props.resetClient();
  this.props.resetUser();
};

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

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

reset = async () => {
  await this.props.resetFilter();
  await this.props.resetClient();
  await this.props.resetUser();
};

谢谢:)

【问题讨论】:

  • 重置函数返回一个承诺?
  • @MohammedAshfaq 不,他们不返回承诺。它们是在 reducer 中重置值的操作

标签: javascript reactjs async-await es6-promise


【解决方案1】:

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

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

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

reset = async () => {
  await this.props.resetFilter();
  await this.props.resetClient();
  await this.props.resetUser();
};

或者如果你想让那些异步函数交错Promise.all

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

如果您不等待第一个示例中的承诺:

reset = () => {
  this.props.resetFilter();
  this.props.resetClient();
  this.props.resetUser();
};

那么这三个调用的承诺链被破坏了,这可能看起来不是一个问题,特别是如果你假设它们总是解决。但如果其中一个 Promise 被拒绝,可能会导致未处理的拒绝。

【讨论】:

    【解决方案2】:

    此函数返回 undefined 而不等待所有函数调用都被解决。

    reset = () => {
      this.props.resetFilter();
      this.props.resetClient();
      this.props.resetUser();
    };
    

    如果您想确保只有在所有调用都已解决时才返回值,您需要等待(或链式承诺,或...)

    因此

    reset = async () => {
      await this.props.resetFilter();
      await this.props.resetClient();
      await this.props.resetUser();
    };
    

    是存档所需行为的一种正确方法。

    【讨论】:

      猜你喜欢
      • 2019-06-16
      • 2013-08-10
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      • 2023-03-10
      • 2020-10-04
      相关资源
      最近更新 更多