Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force gulp calls to run synchronously?

I want the gulp calls below to run synchronously, one after the other. But they do not follow an order.

The run-sequence node module doesn't help here, as I'm not trying to run gulp tasks in series (i.e. it has syntax similar to gulp.task("mytask", ["foo", "bar", "baz"] etc.), but rather gulp "calls" in series, as you see below.

gulp.task("dostuff", function (callback) {

  gulp
    .src("...")
    .pipe(gulp.dest("...");

  gulp
    .src("...")
    .pipe(gulp.dest("...");

  gulp
    .src("...")
    .pipe(gulp.dest("...");

  callback();
});

How do I make them run one after the other?

like image 441
h bob Avatar asked Dec 13 '14 14:12

h bob


People also ask

Is gulp synchronous?

Each gulp task is an asynchronous JavaScript function - a function that accepts an error-first callback or returns a stream, promise, event emitter, child process, or observable (more on that later). Due to some platform limitations, synchronous tasks aren't supported, though there is a pretty nifty alternative.

Is gulp SRC async?

Gulp functions are async, so they need to be awaited, but since they aren't promises, you have to wrap them in one.

What is a Gulpfile?

A gulpfile is a file in your project directory titled gulpfile. js (or capitalized as Gulpfile. js , like Makefile), that automatically loads when you run the gulp command.


2 Answers

You can use async as a control flow for your calls to get them in only one task, also avoiding you to get a "pyramid effect". So something like this should be good for your use-case:

var async = require('async');

gulp.task('yeah', function (cb) {
  async.series([
    function (next) {
      gulp.src('...')
        .pipe(gulp.dest('...')
        .on('end', next);
    },
    function (next) {
      gulp.src('...')
        .pipe(gulp.dest('...')
        .on('end', next);
    },
    function (next) {
      gulp.src('...')
        .pipe(gulp.dest('...')
        .on('end', next);
    }
  ], cb);
});

That will also allow you to have some error handling and target better where a problem occured.

like image 60
Preview Avatar answered Oct 19 '22 03:10

Preview


Well, it's just streams so you could listen for the end event (Watch out for the pyramid of doom!)

gulp.task("dostuff", function (callback) {

  gulp
    .src("...")
    .pipe(gulp.dest("..."))
    .on('end', function () {

      gulp
        .src("...")
        .pipe(gulp.dest("..."))
        .on('end', function () {

          gulp
            .src("...")
            .pipe(gulp.dest("..."))
            .on('end', callback);

        });
    });
});

But it's probably a better pattern to split it up in multiple tasks each one with a dependency on the previous one.

like image 4
Jan Avatar answered Oct 19 '22 03:10

Jan