17

Just a simple question to clarify what does parameter "done" in a gulp task do?

I understand, this is the callback in task function as shown below.

gulp.task('clean', function(done) {
    // so some stuff
    creategulptask(cleantask(), done);
});

But what is the reason to pass it?

Nexus23
  • 6,195
  • 9
  • 50
  • 67

1 Answers1

26

The gulp documentation specifies something similar to the following:

var gulp = require('gulp');

// Takes in a callback so the engine knows when it'll be done
// This callback is passed in by Gulp - they are not arguments / parameters
// for your task.
gulp.task('one', function(cb) {
    // Do stuff -- async or otherwise
    // If err is not null and not undefined, then this task will stop, 
    // and note that it failed
    cb(err); 
});

// Identifies a dependent task must be complete before this one begins
gulp.task('two', ['one'], function() {
    // Task 'one' is done now, this will now run...
});

gulp.task('default', ['one', 'two']);

The done argument is passed into the callback function you use to define your tasks.

Your task function can "accept a callback" function parameter (often this function parameter is named done). Executing that done function tells Gulp "a hint to tell it when the task is done".

Gulp needs this hint if you want to order a series of tasks that depend on each other, as shown in the above example. (i.e. task two won't begin until task one calls cb()) In essence, it stops tasks from running concurrently if you don't want them to.

You can read more about this here: https://github.com/gulpjs/gulp/blob/master/docs/API.md#async-task-support

Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
Seer
  • 5,226
  • 5
  • 33
  • 55
  • 1
    Nicely Explained. Thanks @Seer – Nexus23 Apr 17 '15 at 15:47
  • 2
    Just curious, how does gulp check and know, if the function I give to him has a parameter or not? How is this possible in Javascript? This sounds like reflection. – Holger Thiemann Jan 19 '16 at 15:37
  • The callback is particularly useful if you need to run an async process inside the task, while you want the task to wait for that to complete, before returning. Otherwise, just returning the stream might be enough. See also https://github.com/gulpjs/gulp/blob/master/docs/API.md#async-task-support – grtjn Feb 11 '16 at 13:39
  • 2
    @HolgerThiemann internally, gulp can receive the function passed and check its `length` attribute to see the amount of expected parameters. – Patrick Roberts Jul 05 '16 at 16:49
  • Encourage people to check out the documentation; there are 2 alternatives to the "done callback" technique. First alternative: return a [stream](https://nodejs.org/api/stream.html). Second alternative: return a [promise.](https://github.com/kriskowal/q) – Nate Anderson Mar 29 '17 at 21:48