nuno
nuno

Reputation: 1791

How to run Grunt tasks synchronously (programmatically)?

I want a task that runs sub-tasks synchonously in a loop, and such loop is broken when a sub-task changes the value of a flag.

Here is a sample of what I'm trying to do:

grunt.registerTask('complexTask', 'Run sub-tasks synchronously.', function () {
    var value;
    do {
        // 'changeValueTask' task sets 'importantValue'
        grunt.task.run(['preTask', 'changeValueTask', 'postTask']);
        value = grunt.config('importantValue');
    } while (!value);
    // ... end task
});

What I want to get out of this is

Is it possible to achive this?

Note: the closest thing I could find after some research was that Grunt allows to define that a given task B fails if task A is not done (with grunt.task.requires: grunt.task.requires('A')).

Upvotes: 2

Views: 1370

Answers (1)

nuno
nuno

Reputation: 1791

This is how we fixed it (following in the footsteps of Bergi's comment):

Instead of trying to explicitly loop and run tasks on Grunt, it is best to use the natural task-chaining mechanism of Grunt to ensure one task is executed after the other, like so

grunt.task.run(['preTask', 'changeValueTask', 'postTask']);

Assuming this, we used recursion at the end of each postTask to check if we need to run it again (by checking the importantValue flag) - we achieve this with a task on its own

grunt.task.run(['preTask', 'changeValueTask', 'postTask', 'taskCheck']);

grunt.registerTask('taskCheck', 'Recursive task.', function() {
  var value = grunt.config('importantValue');
  if (value) {
    // done... work with value
  } else {
    // keep running
    grunt.task.run(['preTask', 'changeValueTask', 'postTask', 'taskCheck']);
  }
});

As an improvement we can bootstrap this whole recursion on a task to avoid unnecessary cluttering and isolate this looping behavior:

grunt.registerTask('runValueTask', 'Bootstrap to start recursion.', function() {
  grunt.task.run(['preTask', 'changeValueTask', 'postTask', 'taskCheck']);
});

grunt.registerTask('taskCheck', 'Recursive task.', function() {
  var value = grunt.config('importantValue');
  if (value) {
    // done... work with value
  } else {
    // keep running
    grunt.task.run('runValueTask');
  }
});

Upvotes: 2

Related Questions