Search code examples
javascriptnode.jsasynchronousgulp

How does Gulp know when an asynchronous dependent task is complete (specifically, 'gulp-connect')?


Learning Gulp, I see this simple example that runs a second task after a first is complete:

var gulp = require('gulp');
var connect = require('gulp-connect');

// First task
gulp.task('connect', function() {
    // No callback is provided to Gulp to indicate when the server is connected!
    connect.server();
});

// Second task runs after the first task 'completes'
gulp.task('open', ['connect'], function() {

    // v v v
    // Question: since no callback is provided to indicate when 'connect' completes,
    // how does Gulp know when to run this task?

    // Some task here...
});

My question is straightforward.

I think that the connect.server() task must be asynchronous, so that somewhere in its implementation is:

http.createServer(function(request, response) {
    // Presumably, before the first request can be received,
    // there must be an asynchronous delay while the server initializes

    /// ...handle HTTP requests here...
});

I assume that there is an asynchronous delay before the first request can be received in that first task - and only when requests are ready to be received should the first task be considered 'complete', so that Gulp can run the second task.

Given this, how does Gulp know that the server is fully connected and receiving requests so that it knows to run the second task?

I do not see a callback provided to Gulp that can be used by Gulp as a trigger to indicate that the next task is ready to run.


Solution

  • In this case, I don't believe you could be 100% sure for 2 reasons.

    The first is that you're not passing a callback to your connect task. The second is that you're not using a callback in your server.listen()

    Gulp allows tasks to pass a callback in to the task function for explicit signaling that a task is complete.

    You could do something like this

    gulpfile

    gulp.task('connect', function(done) {
        connect.server(function() {
            return done();
        });
    });
    

    server

    module.exports = function(callback) {
        let server = http.createServer();
        let port = process.env.PORT || 3000;
    
        // all of your routes and server logic
    
        server.listen(port, function() {
            console.log('listening on ' + port);            
            if (callback)
                return callback;            
        });
    }