Ben*_*son 6 asynchronous node.js yeoman-generator
我正在学习如何写一个自耕农发电机.我对以下代码有疑问.它表示通过var done = this.async();在回调中添加并调用该方法,我们可以使该函数askFor()成为异步函数.有人可以解释一下原因吗?
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));
}
Run Code Online (Sandbox Code Playgroud)
这是代码 this.async
this.async = function() {
return function() {};
}
Run Code Online (Sandbox Code Playgroud)
只是通过纯粹的巧合寻找其他东西而陷入这个问题.
实际上,this.async在run阶段期间将覆盖每个方法,以延迟执行直到完成或同步运行.
您可以在此处阅读相关代码行:https: //github.com/yeoman/generator/blob/master/lib/base.js#L372-L393
所以基本上,在幕后Yeoman总是叫回调.当你打电话时,this.async()我们保留一个引用变量并返回回调.如果你不调用它,我们会在函数结束后手动调用回调.
| 归档时间: |
|
| 查看次数: |
2815 次 |
| 最近记录: |