Gulp task return 的做用

最近的项目须要写gulp的task,大概的做用是去先去svn取一些文件,而后基于这些文件去生成另外一些文件。因为文件之间有依赖关系,只有tasks之间也存在前后顺序,只有当前一个task结束了,后一个task才能开始。html

使用run-sequence(https://www.npmjs.com/package...)这个插件来保证顺序,可是发现即便使用了这个插件,task之间仍然是异步的,后来网上搜索了下(https://stackoverflow.com/que...),获得如下结论,缘由是个人gulp task没有return,若是不return 系统不知道何时task结束(Without return the task system wouldn't know when it finished.)因此即便是在run-sequence这个插件下,也没法保证按指定顺序执行。npm

结论: gulp的task都要保证有return或者callback,去通知系统任务结束。(make sure they either return a stream or promise, or handle the callbackgulp

var gulp = require('gulp');
var runSequence = require('run-sequence');
var del = require('del');
var fs = require('fs');
 
// This will run in this order:
// * build-clean
// * build-scripts and build-styles in parallel
// * build-html
// * Finally call the callback function
gulp.task('build', function(callback) {
  runSequence('build-clean',
              ['build-scripts', 'build-styles'],
              'build-html',
              callback);
});
 
// configure build-clean, build-scripts, build-styles, build-html as you wish,
// **but make sure they either return a stream or promise, or handle the callback**
// Example:
gulp.task('build-clean', function() {
    // Return the Promise from del()
    return del([BUILD_DIRECTORY]);
//  ^^^^^^
//   This is the key here, to make sure asynchronous tasks are done!
});
gulp.task('build-scripts', function() {
    // Return the stream from gulp
    return gulp.src(SCRIPTS_SRC).pipe(...)...
//  ^^^^^^
//   This is the key here, to make sure tasks run to completion!
});

gulp.task('callback-example', function(callback) {
    // Use the callback in the async function
    fs.readFile('...', function(err, file) {
        console.log(file);
        callback();
//      ^^^^^^^^^^
//       This is what lets gulp know this task is complete!
    });
});
相关文章
相关标签/搜索