javascript - 自耕农生成器 : copy or template doesn't work from inside async callback

标签 javascript node.js asynchronous yeoman yeoman-generator

在 yeoman 生成器内,我尝试根据外部网络资源的状态进行条件复制。我的问题是 yeoman copy 命令(src.copytemplate)在异步回调内部调用时似乎没有执行任何操作,例如来自 http 请求的回调。

示例代码,位于 yeoman.generators.NamedBase.extend block 内:

main: function(){  
//-> here this.copy('inlocation','outlocation') works as expected
var that = this;

var appName = ...
var url = ...

var req = http.request(url, function(res){
//-> here that.copy('inlocation','outlocation') DOES NOT work
    res.on('data', function (data) {
        //console.log('Response received, onData event');
        //-> here that.copy('inlocation','outlocation') DOES NOT work
    });
    //-> here that.copy('inlocation','outlocation') DOES NOT work
});
req.on('error',function(error){
    //...
});
req.end();
//-> here this.copy('inlocation','outlocation') works as expected, once again

注意标有“//-->”注释的位置作为引用点 - 当它工作时,它会按预期工作。如果没有,控制台上就没有任何输出(因此 that.copy 似乎作为一个函数存在,事实上我可以断言 typeof that.copy === 'function' !),没有错误消息,只是没有创建文件(通常的文件创建消息也丢失了,这是正常工作命令的一个特征)。

使用 call 或 apply 将显式 this 引用传递给函数不会改变行为,将 this 绑定(bind)到异步函数也不会改变行为。

此行为的解释是什么?如何以这种异步方式进行复制调用?

最佳答案

根据 Eric MORAND 的评论,我会将我找到的解决方案作为单独的答案发布,而不是对原始帖子进行编辑,希望它会更容易找到:

我找到了一个解决方案,使用 yeoman RunContext 的 async() 函数。 (请参阅 api 文档 here )异步代码开头的以下行:

var done = this.async();

然后在我想运行复制之前调用 done() 使其行为符合最初的预期。

关于javascript - 自耕农生成器 : copy or template doesn't work from inside async callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26508055/

相关文章:

javascript - 当只有一个选项时,显示选择列表中的所有选项不起作用

javascript - 为什么我的简单循环不能在 jsfiddle.net 中运行?

node.js - 具体案例 : UNABLE_TO_VERIFY_LEAF_SIGNATURE

javascript - 连续传递样式和并发

c# - 异步和等待 - 单元测试问题

javascript - Leaflet - 创建自定义按钮来绘制

javascript - 如何传递整数来创建新变量名?

node.js - express 4.0 , 带有奇怪警告信息的 express-session

node.js - Passport.js session 丢失

c# - 不等待 HttpClient 使用时会发生什么