[英]How to make Grunt wait for a task to finish before running another?
我相信你的問題在於這個任務:
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()調用允許任何后續任務運行。
有很多方法可以將調用轉移到異步並完成循環。 快速谷歌搜索類似於: 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文檔中所讀到的那樣:
如果任務是異步的,則必須調用this.async方法來指示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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.