Reputation: 2209
For example, I read Grunt documentation on Creating Tasks. In "Tasks can be asynchronous" section, there is a use case of "done" function, I wonder why do we need that.
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);
});
Upvotes: 2
Views: 13248
Reputation: 11318
Grunt internally has a flag that determines if a task should be marked as complete when the task-function finishes or if it should be handled asynchronously. By default Grunt runs tasks synchronously and the this.async()
call toggles this flag.
The "synchronous-by-default" design decision was probably made to make simple tasks easier to write where you could use fs.writeSync etc., which is definitely a valid approach albeit gets in the way with at least the kind of tasks that I usually write nowadays.
Grunt was also created before Promises became a viable solution for callback-hells, so there's that too.
I'm pretty sure there are also other reasons for this that I'm not aware of :)
Upvotes: 0
Reputation: 6311
It's the only way for Grunt to know when your task is complete when doing async work.
This SO Post provides quite a bit of detail of what async in JS means and how to work with it.
Basically, setTimeout
calls your callback function 1 second later. However, grunt has no idea when your callback is complete, as setTimeout
itself returns immediately once it is called. Therefore, the done()
function exists to provide you a way to tell grunt that your task is complete, whenever that may be.
Upvotes: 3