Search code examples
javascriptreactjsasync-awaites6-promise

In Javascript does async await wait for all nested functions to complete?


In the example below I need to reset some values before making the fetchData call in the fetch method. Does async await wait for all functions in the reset method to complete before continuing?

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

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

Or do you have to do something like below?

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

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

Thanks :)


Solution

  • async/await does not magically deal with asynchronous function. It is a syntax addition that allows you to easier work with promises.

    So whenever a function returns a Promise, you need to wait for it explicitly.

    Either by writing await in front of each if you want to execute them in order, as you have shown in your second example:

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

    Or if you want to allow that those asynchounous function to interleave Promise.all:

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

    If you do not wait for the Promises like in your first example:

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

    then the promise chain is broken for that three call, this might not look like be a problem at first, especially if you assume that they always resolve. But can result in an unhandled rejection if on of this promises is rejected.