在JavaScript中,async await是否等待所有嵌套函数完成?

6
在下面的示例中,我需要在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();
};

感谢您的选择 :)

重置函数会返回一个 Promise 吗? - Mohammed Ashfaq
@MohammedAshfaq 不,它们不返回 Promise。它们是一些操作,将重置 reducer 中的值。 - theseboys
2个回答

8

async/await 并不能神奇地处理异步函数。它只是一个语法增强,使您更容易使用 promises。

因此,每当一个函数返回一个 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()
  ])
};

如果您不像第一个示例中一样等待Promise:
reset = () => {
  this.props.resetFilter();
  this.props.resetClient();
  this.props.resetUser();
};

如果其中一个调用出现问题,那么这个 Promise 链就会被中断。起初这看起来可能不是问题,特别是当你假设它们始终能够成功时。但是,如果其中一个 Promise 被拒绝,就有可能导致未处理的拒绝。


1
该函数在所有函数调用都被解决之前返回undefined。
reset = () => {
  this.props.resetFilter();
  this.props.resetClient();
  this.props.resetUser();
};

如果您想确保仅在所有调用都已完成时返回值,则需要等待(或链接 promises,或...)。
因此,
reset = async () => {
  await this.props.resetFilter();
  await this.props.resetClient();
  await this.props.resetUser();
};

有一种正确的方式可以归档您所需的行为。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接