【问题标题】:this.async() in yeoman-generatoryeoman-generator 中的 this.async()
【发布时间】:2015-10-06 23:07:15
【问题描述】:

我正在学习如何编写一个 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));
}

这里是this.async的代码

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

【问题讨论】:

  • 你已经了解同步和异步javascript的区别了吗?
  • 是的,我明白其中的区别。但我不明白它是如何通过使用this.async() 使代码在这里异步的

标签: node.js asynchronous yeoman-generator


【解决方案1】:

偶然发现这个问题只是为了寻找其他东西。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多