【问题标题】:Exception when passing gulp callback directly to promise将 gulp 回调直接传递给 Promise 时出现异常
【发布时间】:2016-01-03 11:07:12
【问题描述】:

我已经定义了 gulp 任务 'clean-code' 和函数 'clean' 如下

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

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

出现错误

/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)

但是当我以以下方式重构函数“干净”时,一切正常

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

我不明白区别在哪里以及为什么用 f 完成包装会使任务正常工作

【问题讨论】:

  • 如果我不得不猜测 - done 接受参数 - 第一个参数是 Error 表示突然完成。这是节点回调约定。如果你在then 之后调用done 并且del 有一个返回值——它会失败。如果你使用 bluebird promises,你会使用 del(path).nodeify(done) 来克服这个问题。

标签: javascript callback gulp promise del


【解决方案1】:

假设您使用的是this 库,那么为del 函数返回的Promise 实际上返回一个参数paths 毫无价值。您可以像这样验证此参数是否存在:

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

在您的代码中:

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

会将paths 参数转发给 done 函数,该函数会将其解释为导致应用程序崩溃的错误参数。通过自己调用done(),不会转发任何参数并且任务将被正确执行。

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    相关资源
    最近更新 更多