gpt4 book ai didi

javascript - Gulp 如何知道异步相关任务何时完成(具体来说, 'gulp-connect' )?

转载 作者:太空宇宙 更新时间:2023-11-04 00:39:06 25 4
gpt4 key购买 nike

学习 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() {

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

我的问题很简单。

我认为 connect.server() 任务必须是异步的,因此其实现中的某个位置是:

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

我假设在第一个任务中接收第一个请求之前存在异步延迟 - 并且只有当请求准备好接收时才应将第一个任务视为“完成”,以便 Gulp 可以运行第二个任务。

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

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

最佳答案

在这种情况下,我认为您不能 100% 确定,原因有两个。

首先是您没有将回调传递给 connect 任务。第二个是您没有在 server.listen()

中使用回调

Gulp 允许任务将回调传递给 task function用于明确表示任务已完成。

你可以做这样的事情

gulp文件

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

关于javascript - Gulp 如何知道异步相关任务何时完成(具体来说, 'gulp-connect' )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37661770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com