如何让Grunt在运行另一个任务之前等待一个任务完成
How to make Grunt wait for a task to finish before running another?
这是我的Gruntfile和输出。
在输出中可以看到,有几个与异步任务相关的问题:- 呼叫
-
imagemin
,下一个直接进入。这使得它的输出出现在任务的末尾,这是相当混乱的; -
build
为自定义任务,为,使用var done = this.async()
,完成命令后调用done()
;然而,这只有在我单独运行任务时才能正常工作;与其他任务一起运行会使它也异步运行; -
build
运行后,jasmine
没有什么可测试的,因此是无用的。
有办法修复这个行为吗?
我认为你的问题是在这个任务上:
grunt.registerTask('prepare-dist', 'Creates folders needed for distribution', function() {
var folders = ['dist/css/images', 'dist/imgs/icons'];
for (var i in folders) {
var done = this.async();
grunt.util.spawn({ cmd: 'mkdir', args: ['-p', folders[i]] }, function(e, result) {
grunt.log.writeln('Folder created');
done();
});
}
});
如果你有多个文件夹,async()和done()都将被多次调用。Async被实现为一个简单的标志(true/false),并且意味着被调用一次。第一个done()调用允许任何后续任务运行。
有很多方法可以将调用移到async并在循环外完成。在谷歌上快速搜索一下:nodejs how to callback when a series of async tasks are complete
会给你一些额外的选择。简单地说几句。肮脏的)例子:
// Using a stack
(function() {
var work = ['1','2','3','4','5']
function loop(job) {
// Do some work here
setTimeout(function() {
console.log("work done");
work.length ? loop(work.shift()) : done();
}, 500);
}
loop(work.shift());
function done() {
console.log('all done');
}
})();
——或——
// Using a counter (in an object reference)
(function() {
var counter = { num: 5 }
function loop() {
// Do some work here
setTimeout(function() {
--counter.num;
console.log("work done");
counter.num ? loop() : done();
}, 500);
}
loop();
function done() {
console.log('all done');
}
})();
您可以在Grunt文档中读到:
如果任务是异步的,则此。必须调用异步方法来指示哼哼着等待。它返回一个"完成"函数的句柄任务完成时调用。
和一个简短的例子类似:
// Tell Grunt this task is asynchronous.
var done = this.async();
// Your async code.
fetchData(url).then( data => {
console.log(data);
done();
}).catch( error => {
console.err(error);
done(false); // false instructs Grunt that the task has failed
});
相关文章:
- 如何在另一个任务中正确使用延迟的gump任务返回的值
- 从另一个grunt文件加载grunt任务
- 我需要将一个参数从另一个任务传递给gullow任务,或者用runSequence调用的函数替换一个任务
- 从gullow任务运行一个npm脚本
- 循环一个单调乏味的任务
- 一个咕哝的任务能运行其他咕哝的任务吗
- 我如何在谷歌Chrome上打开一个新的弹出窗口,它可以在不经过Windows'任务栏
- 如何让一个按钮根据点击次数执行多个任务?(Javascript)
- 如何将外部 JSON 数据从上一个任务中生成的文件传递到任务
- 一个 HTML 表单,其中包含用于不同任务的多个提交按钮
- 节点群集未将任务分派给另一个可用的工作线程
- 一个 Gulp 任务中的多个同步流
- 我的 gulp usemin 任务缺少一个 js 文件
- 在另一个任务之前异步运行 grunt 任务
- 在Laravel Elixir中创建一个任务,以指定的顺序运行Gulp任务
- 从另一个任务访问Grunt当前任务
- 编写的第一个Grunt插件-即使Grunt.registerMultiTask()名称正确,也找不到任务
- 与另一个grunt任务共享来自自定义grunt任务的数据
- 如何从另一个gull文件.js导入所有任务
- 如何定义一个(内部)任务,而不把它列在“grunt——help”中