代码之家  ›  专栏  ›  技术社区  ›  Piotr Kozak

将gulp回调直接传递给promise时出现异常

  •  0
  • Piotr Kozak  · 技术社区  · 10 年前

    我定义了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)
    

    但当我用以下方式重构了“clean”函数时,一切都正常

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

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

    1 回复  |  直到 10 年前
        1
  •  0
  •   xaviert    10 年前

    假设您正在使用 this 图书馆,诺言为 del 函数实际上返回了一个参数 paths 。您可以验证此参数是否存在,如下所示:

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

    在您的代码中:

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

    将转发 路径 参数,这将把它解释为导致应用程序崩溃的错误参数。通过呼叫 done() 您自己,没有参数被转发,任务将被正确执行。