Search code examples
javascriptcallbackgulppromisedel

Exception when passing gulp callback directly to promise


I've defined gulp task 'clean-code' and function 'clean' as below

gulp.task('clean-code', function (done) {
 var files = ...;
 clean(files, done);
});

function clean (path, done) {
 del(path).then(done);
}

and got error

/usr/local/bin/node /usr/local/lib/node_modules/gulp/bin/gulp.js --color --gulpfile /Users/[path to project]/Gulpfile.js clean-code
[11:45:04] Using gulpfile /Users/[path to project]/Gulpfile.js
[11:45:04] Starting 'clean-code'...
[11:45:04] Cleaning: ./.tmp/**/*.js,./build/**/*.html,./build/js/**/*.js
[11:45:04] 'clean-code' errored after 8.68 ms
[11:45:04] Error
    at formatError (/usr/local/lib/node_modules/gulp/bin/gulp.js:169:10)
    at Gulp.<anonymous> (/usr/local/lib/node_modules/gulp/bin/gulp.js:195:15)
    at emitOne (events.js:77:13)
    at Gulp.emit (events.js:169:7)
    at Gulp.Orchestrator._emitTaskDone (/Users/[path to project]/node_modules/gulp/node_modules/orchestrator/index.js:264:8)
    at /Users/[path to project]/node_modules/gulp/node_modules/orchestrator/index.js:275:23
    at finish (/Users/[path to project]/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:21:8)
    at cb (/Users/[path to project]/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:29:3)

But when I've refactored function 'clean' in the following way everything is ok

function clean (path, done) {
  var f = function () {
    done();
  };
  del(path).then(f);
}

I don't understand where is the difference and why wrapping done with f make the task working


Solution

  • Assuming you're using this library, it's worth nothing that the Promise returned for the del function actually returns an argument paths. You can verify if this argument is present like this:

    function clean (path, done) {
        del(path).then(function(paths) {
            console.log(paths);
            done();
        });
    }
    

    In your code:

    function clean (path, done) {
        del(path).then(done);
    }
    

    will forward the paths argument to the done function, which will interpret it as an error argument causing your application to crash. By calling done() yourselves, no arguments are forwarded and the task will be properly executed.