微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在学习如何写一个自耕农发电机.我对以下代码有疑问.它通过添加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() {};
}

解决方法

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

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

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

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

原文地址:https://www.jb51.cc/nodejs/241151.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐