Gulp如何知道asynchronous依赖任务何时完成(特别是“gulp-connect”)?

学习Gulp,我看到这个简单的例子,在完成第一个任务后运行第二个任务:

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() { // vvv // Question: since no callback is provided to indicate when 'connect' completes, // how does Gulp know when to run this task? // Some task here... }); 

我的问题很简单。

我认为connect.server()任务必须是asynchronous的,所以在其实现的某个地方是:

 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... }); 

我假设在第一个任务中可以接收到第一个请求之前有一个asynchronous延迟,并且只有在第一个任务被认为是“完成”的时候才准备接收请求,这样Gulp才能运行第二个任务。

鉴于此,Gulp如何知道服务器已完全连接并接收请求,以便知道运行第二个任务?

我没有看到提供给Gulp的callback,可以被Gulp用作触发器来指示下一个任务已经准备好运行。

在这种情况下,我不相信你有两个理由可以100%确定。

首先是你没有将callback传递给你的connect任务。 第二个是你没有在你的server.listen()使用callback

Gulp允许任务将callback传递给任务函数,以明确表示任务已完成。

你可以做这样的事情

gulpfile

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

服务器

 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; }); }