如何让Grunt在运行另一个任务之前等待一个任务完成

How to make Grunt wait for a task to finish before running another?

本文关键字:任务 一个 等待 Grunt 运行 另一个      更新时间:2023-09-26

这是我的Gruntfile和输出。

在输出中可以看到,有几个与异步任务相关的问题:
    呼叫
  1. imagemin,下一个直接进入。这使得它的输出出现在任务的末尾,这是相当混乱的;
  2. build为自定义任务,,使用var done = this.async(),完成命令后调用done();然而,这只有在我单独运行任务时才能正常工作;与其他任务一起运行会使它也异步运行;
  3. 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
});