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!
    });
});
相關文章
相關標籤/搜索