问题
I have multiple Gulp tasks that send a series of commands to the shell. The second task is dependent on the first. How do make ensure all commands sent to async.series in the first task are complete before the second task is executed.
gulp.task('task1', function(cb) {
process.chdir(__dirname);
process.chdir('path');
var cmdArray = getCmdsForTask1();
runSeries(cmdArray, 'Task 1');
return cb();
});
gulp.task('task2',['task1'], function() {
process.chdir(__dirname);
process.chdir('task2_path');
var cmd2 = getCmdForTask2();
runSeries([cmd2], 'Task 2');
});
var runSeries = function(cmdArray, taskName) {
async.series(cmdArray, function(err, results) {
results.forEach( function(result) {
gutil.log(gutil.colors.cyan(taskName + ' complete:') + gutil.colors.white(result) );
});
});
};
Thanks Much!
回答1:
You're on the right track using async.series. The one missing piece is you haven't told the original task when it's done.
gulp.task('task1', function(cb) {
process.chdir(__dirname);
process.chdir('path');
var cmdArray = getCmdsForTask1();
runSeries(cmdArray, 'Task 1', cb);
});
gulp.task('task2',['task1'], function(cb) {
process.chdir(__dirname);
process.chdir('task2_path');
var cmd2 = getCmdForTask2();
runSeries([cmd2], 'Task 2', cb);
});
var runSeries = function(cmdArray, taskName, cb) {
async.series(cmdArray, function(err, results) {
results.forEach( function(result) {
gutil.log(gutil.colors.cyan(taskName + ' complete:') + gutil.colors.white(result) );
});
cb(err);
});
};
Note how I took in a callback to each task, and called it when the async.series was complete.
回答2:
Instead of having tasks depend on each other using the [] syntax, you can use a node plugin called run-sequence.
gulp.task('build', function(callback) {
runSequence('build-clean',
['build-scripts', 'build-styles'],
'build-html',
callback);
});
This example means run 'build-scripts' and 'build-styles' in parallel but do not run 'build-html' until both of them are complete
回答3:
I believe what you're looking for is the waterfall function. It will run the first task, then send the results to the second task and so on. From the documentation:
waterfall(tasks, [callback])
Runs the tasks array of functions in series, each passing their results to the next in the array. However, if any of the tasks pass an error to their own callback, the next function is not executed, and the main callback is immediately called with the error.
来源:https://stackoverflow.com/questions/25371192/how-do-i-get-gulp-tasks-to-fire-sequentially-when-firing-shell-commands-in-an-as