简体   繁体   English

所有异步功能都完成后要执行功能吗?

[英]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: 前3/4个是异步功能:

Example: 例:

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

I want to execute this.executeGitCommentCreation(); 我想执行this.executeGitCommentCreation(); last after al the previous have ran. 在al之后的最后一个已经运行。 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? 我应该在前三名前等待还是使用Promise.all?

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 . 有关更多信息,请阅读docs

P/s: Your naming convention is not unified (mixed with camel case and snake case). P / s:您的命名约定不统一(与骆驼箱和蛇箱混合使用)。 I recommend using camelCase on vars/functions, PascalCase on classes, and ALL_CAPS on constants. 我建议在vars / functions上使用camelCase ,在类上使用PascalCase ,在常量上使用ALL_CAPS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM