如何使用Grunt异步运行2同步任务?

时间:2016-04-02 16:35:00

标签: javascript gruntjs

我有2个Grunt任务:A和B.A的执行时间是5秒。 B的执行时间是10秒。

我在预提交脚本中运行这两个任务。两者都是同步的,所以预提交脚本的exec时间是15.我想以某种方式结合这两个任务并异步运行它们。因此,执行预提交只需10秒钟。

有可能吗?

这个地狱不起作用:)。

grunt.registerTask('pre-commit', 'Run sonar and jscs async', function() {
  var done = this.async(),
    _counter = 0,
    asyncTasksCounter = 2,
    asyncHelper = function (foo) {
      setTimeout(function () {
        foo();
        _counter++;
        if (_counter === asyncTasksCounter) {
          done();
        }
      }, 16.66)
    };
  asyncHelper(function () {
    grunt.task.run('A');
  });
  asyncHelper(function () {
    grunt.task.run('B');
  });
});

1 个答案:

答案 0 :(得分:1)

我不会为此使用Grunt。假设您正在使用npm我会单独定义任务,然后使用npm使用shell-executor(Windows和Mac)等方式运行它们。

安装完成后,您将任务添加到package.json的{​​{3}},然后使用npm run [scriptname]运行脚本,例如npm run prepublish

scripts: {
  "precommit": "shell-exec \"grunt sonar\" \"grunt jscs\"",
}

有一个类似的脚本script section,适用于并发任务。

这些模块必要的原因是因为不同的操作系统处理&(并行)和&&(并发)的方式不同,否则你可以这样做:

"precommit": "grunt sonar & grunt jscs",