gulp 中的任务可以这样定义:
gulp.task('foobar', function(callback) { ... });
我试图了解回调函数是什么。它在哪里定义?我可以在运行时传递一些其他函数作为参数吗?它有什么作用?
These docs表示回调参数是对 Orchestrator 任务应异步运行的提示,其中执行回调表示异步任务已完成。
通过一些实验,看起来调用不带参数的回调会返回成功状态,而使用一些字符串调用它会引发错误:
gulp.task('foobar', function(callback) {
callback();
});
gulp.task('bazkad', function(callback) {
callback("some string");
});
(旁白:如何在 StackOverflow markdown 中的代码块之间放置一个断点?)
$ gulp foobar
[09:59:54] Using gulpfile ~\repos\gulpproj\gulpfile.js
[09:59:54] Starting 'foobar'...
[09:59:54] Finished 'foobar' after 56 μs
$ gulp bazkad
[10:05:49] Using gulpfile ~\repos\gulpproj\gulpfile.js
[10:05:49] Starting 'bazkad'...
[10:05:49] 'bazkad' errored after 55 μs
[10:05:49] Error: some string
at formatError (~\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:169:10)
at Gulp.<anonymous> (~\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:195:15)
at Gulp.emit (events.js:107:17)
at Gulp.Orchestrator._emitTaskDone (~\repos\gulpproj\node_modules\gulp\node_modules\orchestrator\index.js:264:8)
at ~\repos\gulpproj\node_modules\gulp\node_modules\orchestrator\index.js:275:23
at finish (~\repos\gulpproj\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:21:8)
at cb (~\repos\gulpproj\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:29:3)
at Gulp.<anonymous> (~\repos\gulpproj\gulpfile.js:35:5)
at module.exports (~\repos\gulpproj\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (~\repos\gulpproj\node_modules\gulp\node_modules\orchestrator\index.js:273:3)
所以,我的问题是:
- 这是回调的唯一功能,如果传递了参数则引发异常,否则成功完成,还是做其他事情?
- 我可以用其他函数覆盖它吗(这样做是否有合理的理由)?
也许我的文档阅读能力不及格(这不会是第一次),但我似乎无法在 API 文档中找到这些问题的答案。
感谢您的帮助。
最佳答案
回调函数来自 Orchestrator(或 Gulp 4 中的新函数 - 承办者),实际上只不过是一个告诉任务系统您的任务“完成”的调用。这就是为什么他们将其更改为
gulp.task('something', function(done) { ... });
在即将发布的文档中更清楚地说明这一点。
为什么需要回调?通常,您在定义任务时会返回一个流:
gulp.task('goodstuff', function() {
return gulp.src('./app/**/*.*')
.pipe(someotherstuff())
.pipe(gulp.dest('./dist');
});
通过返回一个流,任务系统能够计划这些流的执行。但有时,尤其是当您处于回调 hell 或调用一些无流插件时,您无法返回流。这就是回调的用途。让任务系统知道您已完成并继续执行链中的下一个调用。
对于您的问题:
Is this the only functionality of the callback, to raise an exception if passed an argument and to complete successfully otherwise?
不,唯一的功能是让任务系统知道您的任务已完成。
Is there anything else that it does?
没有。
Could I override it with some other function (and would there be any sane reason to do so)?
没有和没有。
Is it possible to pass any other arguments to a gulp task function?
不,但你为什么要这样做?您的服务拥有 JS 文件的全部范围,只需将您的参数放在某个位置即可。
关于node.js - gulp:gulp任务回调函数定义在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29298244/