409

in the snippet like this:

gulp.task "coffee", ->
    gulp.src("src/server/**/*.coffee")
        .pipe(coffee {bare: true}).on("error",gutil.log)
        .pipe(gulp.dest "bin")

gulp.task "clean",->
    gulp.src("bin", {read:false})
        .pipe clean
            force:true

gulp.task 'develop',['clean','coffee'], ->
    console.log "run something else"

In develop task I want to run clean and after it's done, run coffee and when that's done, run something else. But I can't figure that out. This piece doesn't work. Please advise.

3
  • 10
    The run-sequence npm module fixes this problem now - all other answers are now irrelevant - see OverZealous's answer below
    – danday74
    Dec 13, 2015 at 15:39
  • 1
    Gulp 4.0 natively supports running tasks in sequence, rendering run-sequence obsolete - see massanishi's answer below
    – Forivin
    Jan 12, 2017 at 9:36
  • Gulp4 breaks more things than it fixes, it would seem. After battling with it for a few hours, I am back to 3.9.1. I realize major versions can/will break backcompat but with cryptic and useless error messages, i say no thanks. v4 is not ready.
    – Sat Thiru
    Dec 18, 2018 at 22:14

15 Answers 15

414

By default, gulp runs tasks simultaneously, unless they have explicit dependencies. This isn't very useful for tasks like clean, where you don't want to depend, but you need them to run before everything else.

I wrote the run-sequence plugin specifically to fix this issue with gulp. After you install it, use it like this:

var runSequence = require('run-sequence');

gulp.task('develop', function(done) {
    runSequence('clean', 'coffee', function() {
        console.log('Run something else');
        done();
    });
});

You can read the full instructions on the package README — it also supports running some sets of tasks simultaneously.

Please note, this will be (effectively) fixed in the next major release of gulp, as they are completely eliminating the automatic dependency ordering, and providing tools similar to run-sequence to allow you to manually specify run order how you want.

However, that is a major breaking change, so there's no reason to wait when you can use run-sequence today.

11
  • 2
    @OverZealous thanks for the plugin! Btw, the gulp-clean plugin wasn't implementing Streams 2, so it had issues being run as a dependencies. This has been fixed as of release version 0.3.0, my co-worker submitted a PR to convert it over. Jun 10, 2014 at 13:12
  • You don't need a plugin for this, Gulp has a built in syntax for task dependencies!
    – Indolering
    Mar 11, 2015 at 22:32
  • 3
    @Indolering The built-in task dependency functionality does not solve this scenario. Dependent tasks are always run: there's no built in way to run two tasks in a row some of the time, but not every time. run-sequence solves a critical piece of missing functionality in gulp. Mar 12, 2015 at 2:27
  • 2
    Also, task dependencies are not a complete solution. Say I have two gulp tasks that independently run tests using the database. Neither is dependent on the other, but I don't want either of them to run at the same time because they both need to use the database.
    – peterjwest
    Jun 30, 2015 at 14:03
  • 3
    Amazing module - Heres a great explanation of why it is needed - blog.mdnbar.com/gulp-for-simple-build-proccess - This should be the accepted answer
    – danday74
    Dec 13, 2015 at 15:42
376

The only good solution to this problem can be found in the gulp documentation:

var gulp = require('gulp');

// takes in a callback so the engine knows when it'll be done
gulp.task('one', function(cb) {
  // do stuff -- async or otherwise
  cb(err); // if err is not null and not undefined, the orchestration will stop, and 'two' will not run
});

// identifies a dependent task must be complete before this one begins
gulp.task('two', ['one'], function() {
  // task 'one' is done now
});

gulp.task('default', ['one', 'two']);
// alternatively: gulp.task('default', ['two']);
17
  • 6
    For some reason I'm getting ReferenceError: err is not defined trying to run this on a gulp-compass task, am I missing something?
    – waffl
    Jul 30, 2015 at 22:13
  • 11
    @waffl this example uses a callback, which isn't the only way to do this. According to the docs, you can also "return a promise or stream that the engine should wait to resolve or end respectively." So if you return a stream in task one, e.g. return gulp.src('app/**/*.js').pipe(concat(app.js)).pipe(gulp.dest('app/scripts');, the key is to identify task one as a dependent when defining task two: gulp.task('two', ['one'], function() {... Task two will now wait for task one to end before running.
    – esvendsen
    Sep 2, 2015 at 4:59
  • 24
    This creates a tight coupling between 'one' and 'two'. What if you want to run 'two' without running 'one'
    – wilk
    Dec 2, 2015 at 21:36
  • 5
    you define a new task without the dependency ? Dec 2, 2015 at 21:38
  • 8
    Needing two tasks to run sequentially implies a tight coupling.
    – Ringo
    Aug 31, 2016 at 22:55
133

It's not an official release yet, but the coming up Gulp 4.0 lets you easily do synchronous tasks with gulp.series. You can simply do it like this:

gulp.task('develop', gulp.series('clean', 'coffee'))

I found a good blog post introducing how to upgrade and make a use of those neat features: migrating to gulp 4 by example

15
  • 3
    Method of choice for all newcomers. They should really start with gulp 4, skipping all 3.* hassle and wide range of antipatterns.
    – metalim
    Apr 6, 2016 at 21:51
  • 193
    its 2017 and they still did not introduce it. Great. Jan 12, 2017 at 19:53
  • 14
    I don't see the point, really. If you absolutely need A to run only after B runs, then A depends on B. Why can't you just specify that B is a dependency of A? gulp.task('coffee', ['clean'], function(){...}); gulp.task('develop', ['coffee']);
    – musicin3d
    Mar 14, 2017 at 17:59
  • 3
    @musicin3d What you say works, but you're coupling one task necessarily to the previous. For example, I want to be able to build without always having to lint before. It's a better solution to have independent tasks and decide the order of execution with an external tool.
    – AxeEffect
    May 17, 2017 at 16:52
  • 13
    its 2018 and they finally did introduce it. Great.
    – dargmuesli
    Jan 19, 2018 at 0:26
56

I generated a node/gulp app using the generator-gulp-webapp Yeoman generator. It handled the "clean conundrum" this way (translating to the original tasks mentioned in the question):

gulp.task('develop', ['clean'], function () {
  gulp.start('coffee');
});
7
  • 2
    This was the exact (and very simple) I needed. It addresses the scenario where I need to do something like a clean as a preceding dependency to build dependencies without setting clean as a dependency to those tasks. PS: Info about the gulp.start() bit - caveat emptor: github.com/gulpjs/gulp/issues/426
    – Jaans
    Apr 29, 2015 at 14:07
  • That makes sense; a callback after the main task (and it's dependent tasks) have completed. Thanks.
    – markau
    Apr 21, 2016 at 0:16
  • 4
    If someone is wondering why there is no official documentation for gulp.start(), this answer from gulp member explains that: gulp.start is undocumented on purpose because it can lead to complicated build files and we don't want people using it (source: github.com/gulpjs/gulp/issues/426#issuecomment-41208007)
    – thybzi
    Aug 7, 2016 at 19:29
  • 1
    In this case, how can I detect that coffee task is finished? If I don't detect it, develop task will finish earlier than coffee
    – thybzi
    Aug 7, 2016 at 20:42
  • already got the answer from run-sequence source code: gulp.on('task_stop'). See my extended answer for details: stackoverflow.com/a/38818657/3027390
    – thybzi
    Aug 7, 2016 at 21:27
31

run-sequence is the most clear way (at least until Gulp 4.0 is released)

With run-sequence, your task will look like this:

var sequence = require('run-sequence');
/* ... */
gulp.task('develop', function (done) {
    sequence('clean', 'coffee', done);
});

But if you (for some reason) prefer not using it, gulp.start method will help:

gulp.task('develop', ['clean'], function (done) {
    gulp.on('task_stop', function (event) {
        if (event.task === 'coffee') {
            done();
        }
    });
    gulp.start('coffee');
});

Note: If you only start task without listening to result, develop task will finish earlier than coffee, and that may be confusing.

You may also remove event listener when not needed

gulp.task('develop', ['clean'], function (done) {
    function onFinish(event) {
        if (event.task === 'coffee') {
            gulp.removeListener('task_stop', onFinish);
            done();
        }
    }
    gulp.on('task_stop', onFinish);
    gulp.start('coffee');
});

Consider there is also task_err event you may want to listen to. task_stop is triggered on successful finish, while task_err appears when there is some error.

You may also wonder why there is no official documentation for gulp.start(). This answer from gulp member explains the things:

gulp.start is undocumented on purpose because it can lead to complicated build files and we don't want people using it

(source: https://github.com/gulpjs/gulp/issues/426#issuecomment-41208007)

2
  • two coffees to this man! the solution with removing the listener works just perfectly! Sep 22, 2017 at 7:25
  • This really is the answer, or just, "gulp 4". Run sequence is robust.
    – user9844377
    Jun 25, 2018 at 19:10
26

According to the Gulp docs:

Are your tasks running before the dependencies are complete? Make sure your dependency tasks are correctly using the async run hints: take in a callback or return a promise or event stream.

To run your sequence of tasks synchronously:

  1. Return the event stream (e.g. gulp.src) to gulp.task to inform the task of when the stream ends.
  2. Declare task dependencies in the second argument of gulp.task.

See the revised code:

gulp.task "coffee", ->
    return gulp.src("src/server/**/*.coffee")
        .pipe(coffee {bare: true}).on("error",gutil.log)
        .pipe(gulp.dest "bin")

gulp.task "clean", ['coffee'], ->
      return gulp.src("bin", {read:false})
        .pipe clean
            force:true

gulp.task 'develop',['clean','coffee'], ->
    console.log "run something else"
1
  • 4
    THIS should be the correct answer! Returning task did the trick! Thanks man.
    – Dzoukr
    Dec 16, 2015 at 22:22
10

I was having this exact same problem and the solution turned out to be pretty easy for me. Basically change your code to the following and it should work. NOTE: the return before gulp.src made all the difference for me.

gulp.task "coffee", ->
    return gulp.src("src/server/**/*.coffee")
        .pipe(coffee {bare: true}).on("error",gutil.log)
        .pipe(gulp.dest "bin")

gulp.task "clean",->
    return gulp.src("bin", {read:false})
        .pipe clean
            force:true

gulp.task 'develop',['clean','coffee'], ->
    console.log "run something else"
3
  • Thanks for the note on returning! Was going nuts trying to figure out why gulp was src-ing tasks out of order.
    – Andrew F
    Jul 12, 2015 at 21:47
  • This should be the correct answer to avoid tight coupling between tasks. Works well. gulp.series available in 4.0 is probably the best answer, but as of today, 4.0 is not available.
    – wilk
    Dec 2, 2015 at 21:40
  • gulp develop will run clean or coffee first
    – scape
    Oct 5, 2017 at 15:35
9

tried all proposed solutions, all seem to have issues of their own.

If you actually look into the Orchestrator source, particularly the .start() implementation you will see that if the last parameter is a function it will treat it as a callback.

I wrote this snippet for my own tasks:

  gulp.task( 'task1', () => console.log(a) )
  gulp.task( 'task2', () => console.log(a) )
  gulp.task( 'task3', () => console.log(a) )
  gulp.task( 'task4', () => console.log(a) )
  gulp.task( 'task5', () => console.log(a) )

  function runSequential( tasks ) {
    if( !tasks || tasks.length <= 0 ) return;

    const task = tasks[0];
    gulp.start( task, () => {
        console.log( `${task} finished` );
        runSequential( tasks.slice(1) );
    } );
  }
  gulp.task( "run-all", () => runSequential([ "task1", "task2", "task3", "task4", "task5" ));
4

I was searching for this answer for a while. Now I got it in the official gulp documentation.

If you want to perform a gulp task when the last one is complete, you have to return a stream:

gulp.task('wiredep', ['dev-jade'], function () {
    var stream = gulp.src(paths.output + '*.html')
        .pipe($.wiredep())
        .pipe(gulp.dest(paths.output));

    return stream; // execute next task when this is completed
});

// First will execute and complete wiredep task
gulp.task('prod-jade', ['wiredep'], function() {
    gulp.src(paths.output + '**/*.html')
        .pipe($.minifyHtml())
        .pipe(gulp.dest(paths.output));
});

4

For me it was not running the minify task after concatenation as it expects concatenated input and it was not generated some times.

I tried adding to a default task in execution order and it didn't worked. It worked after adding just a return for each tasks and getting the minification inside gulp.start() like below.

/**
* Concatenate JavaScripts
*/
gulp.task('concat-js', function(){
    return gulp.src([
        'js/jquery.js',
        'js/jquery-ui.js',
        'js/bootstrap.js',
        'js/jquery.onepage-scroll.js',
        'js/script.js'])
    .pipe(maps.init())
    .pipe(concat('ux.js'))
    .pipe(maps.write('./'))
    .pipe(gulp.dest('dist/js'));
});

/**
* Minify JavaScript
*/
gulp.task('minify-js', function(){
    return gulp.src('dist/js/ux.js')
    .pipe(uglify())
    .pipe(rename('ux.min.js'))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('concat', ['concat-js'], function(){
   gulp.start('minify-js');
});

gulp.task('default',['concat']); 

Source http://schickling.me/synchronous-tasks-gulp/

3

Simply make coffee depend on clean, and develop depend on coffee:

gulp.task('coffee', ['clean'], function(){...});
gulp.task('develop', ['coffee'], function(){...});

Dispatch is now serial: cleancoffeedevelop. Note that clean's implementation and coffee's implementation must accept a callback, "so the engine knows when it'll be done":

gulp.task('clean', function(callback){
  del(['dist/*'], callback);
});

In conclusion, below is a simple gulp pattern for a synchronous clean followed by asynchronous build dependencies:

//build sub-tasks
gulp.task('bar', ['clean'], function(){...});
gulp.task('foo', ['clean'], function(){...});
gulp.task('baz', ['clean'], function(){...});
...

//main build task
gulp.task('build', ['foo', 'baz', 'bar', ...], function(){...})

Gulp is smart enough to run clean exactly once per build, no matter how many of build's dependencies depend on clean. As written above, clean is a synchronization barrier, then all of build's dependencies run in parallel, then build runs.

3

Gulp and Node use promises.

So you can do this:

// ... require gulp, del, etc

function cleanTask() {
  return del('./dist/');
}

function bundleVendorsTask() {
  return gulp.src([...])
    .pipe(...)
    .pipe(gulp.dest('...'));
}

function bundleAppTask() {
  return gulp.src([...])
    .pipe(...)
    .pipe(gulp.dest('...'));
}

function tarTask() {
  return gulp.src([...])
    .pipe(...)
    .pipe(gulp.dest('...'));
}

gulp.task('deploy', function deployTask() {
  // 1. Run the clean task
  cleanTask().then(function () {
    // 2. Clean is complete. Now run two tasks in parallel
    Promise.all([
      bundleVendorsTask(),
      bundleAppTask()
    ]).then(function () {
      // 3. Two tasks are complete, now run the final task.
      tarTask();
    });
  });
});

If you return the gulp stream, you can use the then() method to add a callback. Alternately, you can use Node's native Promise to create your own promises. Here I use Promise.all() to have one callback that fires when all the promises resolve.

1

To wait and see if the task is finished and then the rest, I have it this way:

gulp.task('default',
  gulp.series('set_env', gulp.parallel('build_scss', 'minify_js', 'minify_ts', 'minify_html', 'browser_sync_func', 'watch'),
    function () {
    }));

Kudos: https://fettblog.eu/gulp-4-parallel-and-series/

1

The very simple and efficient solution that I found out to perform tasks one after the other(when one task gets completed then second task will be initiated) (providing just an example) is :
gulp.task('watch', () =>
gulp.watch(['src/**/*.css', 'src/**/*.pcss'], gulp.series('build',['copy'])) );
This means when you need to run the first-task before second-task, you need to write the second task(copy in this case) in square brackets.
NOTE
There should be round parenthesis externally for the tasks(until you want them to occur simultaneously)

-8

Try this hack :-) Gulp v3.x Hack for Async bug

I tried all of the "official" ways in the Readme, they didn't work for me but this did. You can also upgrade to gulp 4.x but I highly recommend you don't, it breaks so much stuff. You could use a real js promise, but hey, this is quick, dirty, simple :-) Essentially you use:

var wait = 0; // flag to signal thread that task is done
if(wait == 0) setTimeout(... // sleep and let nodejs schedule other threads

Check out the post!

2
  • There's better ways to solve the problem, using setTimeout is not appropriated. You couldn't know exactly how much time a task will take to finish. Sep 1, 2016 at 13:43
  • You really should think before you write any code pff May 12, 2017 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.