如何等待复印行动在Yeoman完成

我在写一个Yeoman生成器,我想复制一个目录。 你可以find下面的代码。 这是工作正常,但是,复制完成后,我想执行进一步的行动,如“NPM安装”。 由于复制是asynchronous完成的,在所有文件被复制之前执行“npm install”。 我如何等待所有复制操作完成?

this.expandFiles('**', { cwd: this.sourceRoot(), dot: true }).forEach(function (el) { this.copy(el, el); }, this); 

.on调用this.copy链并在'end'事件中运行你的函数。

 this.copy(el, el) .on('end', function() { console.log("Copy is complete"); }); 

一个简单的方法是使用一个模块,你可以控制循环的stream程,比如asynchronous,以便知道何时完成。 这里是代码:

 var me = this; var async = require('async'); var array = this.expandFiles('**', { cwd: this.sourceRoot(), dot: true }); async.each(array, function(el, callback) { me.copy(...); // assuming that this copy() is synchronous callback(null); }, function(err) { console.log("done with copying...."); }); 

你可以使用Yeoman的this.async()

首先,获得恢复发电机所需的function:

 var done = this.async(); 

完成复制后(可能在某个callback中done()当您想要恢复生成器时调用done()

文档: https : //yeoman.github.io/generator/RunContext.html