yeoman-generator中的this.async()

我正在学习如何编写一个自动生成器。 我有一个关于下面的代码的问题。 它说通过添加var done = this.async(); 并在稍后的callback中调用方法,我们可以使函数askFor()成为一个asynchronous函数。 有人可以解释为什么吗?

 askFor: function() { var done = this.async(); // Have Yeoman greet the user. this.log(yosay('Welcome to the marvelous Myblog generator!')); var prompts = [{ name: 'blogName', message: 'What do you want to call your blog?', default: 'myblog' }]; this.prompt(prompts, function(props) { this.blogName = props.blogName; done(); }.bind(this)); } 

这是this.async的代码

 this.async = function() { return function() {}; } 

只是在纯粹的巧合中寻找别的东西而陷入这个问题。

实际上,在run阶段,每个方法都会覆盖this.async ,以延迟执行直到完成或者同步运行。

你可以在这里阅读相关的代码行: https : //github.com/yeoman/generator/blob/master/lib/base.js#L372-L393

所以基本上,幕后人总是呼唤回拨。 当你调用this.async()我们保留一个引用variables并返回callback。 如果不调用它,我们会在函数结束后手动调用callback函数。