Executing a function after all async functions have completed?

元气小坏坏 提交于 2019-12-01 10:47:46

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/50263888/executing-a-function-after-all-async-functions-have-completed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!