所有异步功能都完成后要执行功能吗? [英] Executing a function after all async functions have completed?
问题描述
this.validate_label_population();
this.validate_title_prefix();
this.validate_title_suffix();
this.executeGitCommentCreation();
我在构造函数中执行以下函数。前3/4个是异步函数:
I have the following functions executing in a constructor. The top 3/4 are async functions:
示例:
async validate_title_prefix() {
console.log('validate_title_prefix not implemented');
}
我想执行 this.executeGitCommentCreation();
在前一个已运行之后倒数第二次。做这个的最好方式是什么?我应该在前三名前等待还是使用Promise.all?
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?
推荐答案
您可以使用此代码段:
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:您的命名约定不统一(与驼峰箱和蛇箱混在一起)。我建议在变量/函数上使用 camelCase
,在类上使用 PascalCase
,并在 ALL_CAPS
常量。
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.
这篇关于所有异步功能都完成后要执行功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!