Gulp task return 的作用

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

使用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这个插件下,也无法保证按指定顺序执行。

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

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!
    });
});

相关推荐