Why might I be getting “task completion callback c

2019-06-16 09:07发布

Given the following gulp task, why might I be getting the following error?

Error: task completion callback called too many times

function myTask(options, cb) { // cb is the gulp cb
  var serverInstance = http.createServer(dispatch({ /*routes*/ }));

  serverInstance.listen(options.port, function() {
    cb(); // Stack trace identifies this line as throwing the error
  });
}

function partial(fn) {   
    var args = Array.prototype.slice.call(arguments, 1);

    return function() {
        return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
    };
}

gulp.task('task-name', ['task-dependency'], partial(myTask, { port: 8080 }));

Edit:

The following modification makes it work (my question still remains however):

gulp.task('task-name', ['task-dependency'], function(cb) {
  partial(myTask, { port: 8080 })(cb);
});

1条回答
干净又极端
2楼-- · 2019-06-16 09:51

This is because gulp uses heuristics (including the return value of the callback and whether it accepts a callback parameter) to detect async vs sync tasks, and it treats them differently accordingly. My partial function returns a function with no parameters declared that was tricking gulp into thinking it was synchronous when it was asynchronous.

Modifying partial to return a function with a single named parameter solved the issue.

//...
return function(cb) {
  return fn.apply(this, args.concat(slice.call(arguments)));
};
//...
查看更多
登录 后发表回答