node.js – 在yeoman-generator中的this.async()

前端之家收集整理的这篇文章主要介绍了node.js – 在yeoman-generator中的this.async()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习如何写一个自耕农发电机.我对以下代码有疑问.它通过添加var done = this.async()来说并且稍后在回调中调用方法,我们可以使函数askFor()成为异步函数.有人可以解释一下原因吗?
  1. askFor: function() {
  2. var done = this.async();
  3.  
  4. // Have Yeoman greet the user.
  5. this.log(yosay('Welcome to the marvelous Myblog generator!'));
  6.  
  7. var prompts = [{
  8. name: 'blogName',message: 'What do you want to call your blog?',default: 'myblog'
  9. }];
  10.  
  11. this.prompt(prompts,function(props) {
  12. this.blogName = props.blogName;
  13.  
  14. done();
  15. }.bind(this));
  16. }

这是this.async的代码

  1. this.async = function() {
  2. return function() {};
  3. }

解决方法

只是通过纯粹的巧合寻找其他东西而陷入这个问题.

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

您可以在此处阅读相关代码行:
https://github.com/yeoman/generator/blob/master/lib/base.js#L372-L393

所以基本上,在幕后Yeoman总是叫回调.当你调用this.async()时,我们保留一个引用变量并返回回调.如果你不调用它,我们会在函数结束后手动调用回调.

猜你在找的Node.js相关文章