h bob
h bob

Reputation: 3780

Gulp tasks not running in series

I'm following the official docs, but my gulp tasks aren't running in series.

gulp.task("mytask", ["foo", "bar", "baz"]);

gulp.task("foo", function (callback) {
  gulp
    .src("...")
    .pipe(changed("..."))
    .pipe(gulp.dest(function (file) {
      // ...stuff
      return "...";
    }))
    .on("end", function() {
      // ...stuff
      callback();
    });
});

gulp.task("bar", function (callback) {
  //...
});

gulp.task("baz", function (callback) {
  //...
});

But my output looks like this:

Starting 'mytask'...
Starting 'foo'...
Starting 'bar'...                   // <-- foo is not done yet!
Finished 'foo'
Finished 'bar'
Starting 'baz'...
Finished 'baz'
Finished 'mytask'

How do I get them to run in order?

Upvotes: 2

Views: 6461

Answers (2)

user254694
user254694

Reputation: 1612

This answer should be updated to reflect Gulp 4 way of running tasks in a series.

If you want Gulp tasks to run in a series you should use gulp.series to run them, and if you want them to run parallel gulp.parallel.

In using Gulp series you would do something like the following:

gulp.task("mytask", gulp.series(foo, bar, baz));

Those other tasks would probably no longer be tasks but instead consts, like

  const foo = () => {
     return gulp.src("...")
     .pipe(changed("..."))
     .pipe(gulp.dest(function (file) {
      // ...stuff
      return "...";
    }));
  }

hence the reason why the series lists the constants instead of some strings. In moving to Gulp 4 there would probably be other problems arising, but the fixes for a simple gulp file like this one are easy to make.

simple tutorial on gulp 4 https://codeburst.io/switching-to-gulp-4-0-271ae63530c0

Upvotes: 3

JMM
JMM

Reputation: 26787

If you want them to run in series you currently have to use the task dependency system, e.g.:

gulp.task("mytask", ["foo", "bar", "baz"]);

gulp.task("foo", function (callback) {
  //...
  callback(...);
});

gulp.task("bar", ['foo'], function (callback) {
  //...
  callback(...);
});

gulp.task("baz", ['bar'], function (callback) {
  //...
  callback(...);
});

It's clunky. I think it's going to be addressed in a future version.

Depending on the situation you could return a promise or event stream instead of passing in and calling a callback.

I suppose I should mention that the run-sequence module is an option as of right now. But the task dependency system illustrated above is the mechanism currently provided by gulp itself. See this comment re: run-sequence and the future of task sequencing in gulp.

Upvotes: 8

Related Questions