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

时间:2013-03-31 22:50:01

标签: javascript node.js asynchronous gruntjs

这是我的Gruntfileoutput

正如您在输出中看到的,有几个与异步任务相关的问题:

  1. imagemin被召唤,下一个直接前进。这使得它的输出出现在任务的最后,这是非常混乱的;
  2. build,这是一项自定义任务, 使用var done = this.async()并在完成命令后调用done();但是,如果我单独执行任务,这只能正常工作;使用其他任务运行它也会使它也运行异步;
  3. 如果build稍后运行,则jasmine无需测试,因此无用。
  4. 有没有办法解决这种问题?

2 个答案:

答案 0 :(得分:8)

我相信你的问题在于这个任务:

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');
    }
})();

答案 1 :(得分:0)

您可以阅读Grunt documentation

  

如果任务是异步的,则必须调用this.async方法来指示   咕噜等待。它返回一个应该是“完成”函数的句柄   在任务完成时调用。

一个简短的例子类似于:

// 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
});
相关问题