Asynchronous tasks in grunt.registerTask

房东的猫 提交于 2020-01-24 17:38:25

问题


I need to call two functions within grunt.registerTask, but the second function has to be called after the first function is done.

So I was wondering if we can use callbacks or promises or other asynchronous mechanisms within grunt.registerTask.

(More specifically, I need to launch karma in my first function call, and run karma in the second function call (to execute the initial unit tests). But in order to run karma, I need to launch it first. And that's what I'm missing.)


回答1:


I had this:

grunt.registerTask("name_of_task", ["task_a", "task_b", "task_c"]);

And "task_b" had to be executed after "task_a" was done. The problem is that "task_a" is asynchronous and returns right away, so I needed a way to give "task_a" a few seconds to execute.

The solution:

grunt.registerTask("name_of_task", ["task_a", "task_b:proxy", "task_c"]);

grunt.registerTask("task_b:proxy", "task_b description", function () {
        var done = this.async();

        setTimeout(function () {
            grunt.task.run("task_b");
            done();
        }, 2000);
    });
};



回答2:


From http://gruntjs.com/creating-tasks:

Tasks can be asynchronous.

grunt.registerTask('asyncfoo', 'My "asyncfoo" task.', function() {
  // Force task into async mode and grab a handle to the "done" function.
  var done = this.async();
  // Run some sync stuff.
  grunt.log.writeln('Processing task...');
  // And some async stuff.
  setTimeout(function() {
    grunt.log.writeln('All done!');
    done();
  }, 1000);
});



回答3:


For the sake of simplicity... having this Grunfile.js

grunt.registerTask('a', function () {

    let done = this.async();

    setTimeout(function () {
        console.log("a");
        done();
    }, 3000);
});

grunt.registerTask('b', function () {

    let done = this.async();

    console.log("b1");

    setTimeout(function () {
        console.log("b2");
        done();
    }, 3000);

    console.log("b3");
});

grunt.registerTask('c', function () {
    console.log("c");
});

grunt.registerTask("run", ["a", "b", "c"]);

and then running run task, will produce the following output

Running "a" task
a

Running "b" task
b1
b3
b2 <-- take a look here

Running "c" task
c

Done.

The command is executed in this order

wait 3000 ms

console.log("a")

console.log("b1")

console.log("b3")

wait 3000 ms

console.log("b2")

console.log("c")



来源:https://stackoverflow.com/questions/30917211/asynchronous-tasks-in-grunt-registertask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!