Search code examples
javascriptpromisees6-promise

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?


Solution

  • 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.