【发布时间】:2014-12-02 09:51:54
【问题描述】:
如果我执行以下操作:
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
});
grunt.registerTask('myAsync','An async test task',function(){
var done = this.async();
setTimeout(function(){
console.log('This is my async task');
done();
},1000);
});
grunt.registerTask('myTask','A test task',function(){
grunt.task.run('myAsync');
console.log('This is my task');
});
grunt.registerTask('default', ['myTask']);
};
输出是:
Running "myTask" task
This is my task
Running "myAsync" task
This is my async task
所以“myTask”没有等待“myAsync”完成。我希望“myTask”等待“myAsync”。想出了以下方法,但不确定是否可以这样做:
module.exports = function(grunt) {
// Project configuration.
grunt.myAsync = function myAsync(callback){
var done = this.async();
setTimeout(function(){
console.log('This is my async task');
callback();
done();
},1000);
};
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
});
grunt.registerTask('myAsync','An async test task',function(){
grunt.myAsync();
});
grunt.registerTask('myTask','A test task',function(){
var done = this.async();
console.dir(this);
grunt.myAsync.call(this,function(){
console.log('This is my task');
done();
});
});
// Default task(s).
grunt.registerTask('default', ['myTask']);
};
它允许我让 grunt 运行 'myAsync' 或从另一个任务运行它并等待它。
还有其他方法吗?从任务中调用异步任务时,找不到如何等待它们。
[更新]
Kyle 让我走上了正轨,增加了 3 个任务; 1 删除数据库,2,运行测试,3 运行测试并删除数据库。由于任务在队列中运行,第三个任务只需要运行另外两个。而不是让第一个任务(运行测试)调用第二个任务(drop db)。
看起来像这样:
grunt.registerTask('runtests','Runs the integration tests.',function(){
var done = this.async();
setTimeout(function(){
console.log('ran the tests db');
done();
},100);
});
grunt.registerTask('dropdb','Drops the db.',function(){
var done = this.async();
setTimeout(function(){
console.log('droped db');
done();
},100);
});
grunt.registerTask('dropandrun','Runs the integration tests.',function(){
if(!grunt.option('nodrop')){
grunt.task.run('dropsdb');
}
grunt.task.run('runtests');
});
【问题讨论】:
标签: asynchronous gruntjs