Home > Mobile >  Executing asynchronous functions in order, and waiting for for every function to be finished
Executing asynchronous functions in order, and waiting for for every function to be finished

Time:10-29

I need to execute a few async functions in a specific order and also wait for every function until it finish. I'm doing like this:

public async init(): Promise<void> {
try {
 this.executeFunction1().then(() => {
    this.executeFunction2().then(() => {
      this.executeFunction3().then(() => {
        this.executeFunction4().then(() => {
          this.executeFunction5();
        });
      });
    });
  });
} catch (error) {
  this.log.error(`Init failed`);
}

}

All functions are async like:

  public async executeFunction1(): Promise<void> {
   ...........................
  }

Is this a good way (best practice) or is this way is 'Ok'/'not advised' but there is a better way ?

CodePudding user response:

This is a trivial async/await case. Since you're already using async, you're missing the awaits. Something like this will do:

public async init(): Promise<void> {
    try {
        await this.executeFunction1();
        await this.executeFunction2();
        await this.executeFunction3();
        await this.executeFunction4();
        await this.executeFunction5();
    } catch (error) {
        this.log.error(`Init failed`);
    }
}

This kind of programming is the prime reason why async/await was introduced, to facilitate async calls in a pseudo sync way.

CodePudding user response:

If you want to use RxJS you can use concat creation method:

import { concat } from 'rxjs';

concat(
  this.executeFunction1(),
  this.executeFunction2(),
  this.executeFunction3(),
  this.executeFunction4(),
  this.executeFunction5(),
).subscribe();

CodePudding user response:

You probably want something like this:

public async init(): Promise<void> {
  try {
   await this.executeFunction1();
   await this.executeFunction2();
   // etc ...
  } catch (error) {
    this.log.error(`Init failed`);
  }
}
  • Related