Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a function after all async functions have completed?

this.validate_label_population();
this.validate_title_prefix();
this.validate_title_suffix();
this.executeGitCommentCreation();

I have the following functions executing in a constructor. The top 3/4 are async functions:

Example:

  async validate_title_prefix() {
    console.log('validate_title_prefix not implemented');
  }

I want to execute this.executeGitCommentCreation(); last after al the previous have ran. What is the best way to do this? Should I throw await in front of the top 3, or use some sort of Promise.all?

like image 954
John Lippson Avatar asked May 29 '26 19:05

John Lippson


1 Answers

You can use this snippet:

Promise.all([
    this.validate_label_population(), 
    this.validate_title_prefix(), 
    this.validate_title_suffix()
])
.then(function(values) {
    this.executeGitCommentCreation();
}.bind(this));

or you can use arrow function to get the correct context:

Promise.all([
    this.validate_label_population(), 
    this.validate_title_prefix(), 
    this.validate_title_suffix()
])
.then(values => {
    this.executeGitCommentCreation();
});

or you even can cache the this to the outside context:

var _this = this;
Promise.all([
    this.validate_label_population(), 
    this.validate_title_prefix(), 
    this.validate_title_suffix()
])
.then(function(values) {
    _this.executeGitCommentCreation();
});

For more information, read the docs.

P/s: Your naming convention is not unified (mixed with camel case and snake case). I recommend using camelCase on vars/functions, PascalCase on classes, and ALL_CAPS on constants.

like image 133
Duc Filan Avatar answered May 31 '26 08:05

Duc Filan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!