javascript - gulp 任务运行请求显示日志消息太晚了

标签 javascript node.js gulp

您将如何管理以下任务以使消息正确显示? “完成”出现在任务实际完成之前。我猜这是因为请求模块。我试图将请求包装成 promise ,但没有成功。有什么想法吗?

gulp.task('sign', function() {

  util.log(util.colors.yellow('fetching build number from remote URL:'));
  util.log(util.colors.yellow(JENKINS_URL));

  request(JENKINS_URL, function(err, res, body) {
    var parsed = isJson(body);
    var number = parsed.number;

    return gulp.src(path.join(DIST_DIR, '**'))
      .pipe(replace('<%= B =%>', number))
      .on('end', function() {
        util.log(util.colors.yellow('new build number is: ' + number));
      })
      .pipe(replace('<%= V =%>', VERSION))
      .on('end', function() {
        util.log(util.colors.yellow('app version is: ' + VERSION));
      })
      .pipe(gulp.dest(DIST_DIR))
      .on('finish', function() {
        util.log(util.colors.green('operation ended successfully!'));
      });
  });
});

最佳答案

您的任务是异步的(它正在发出请求)。因此,您应该接受一个参数(函数)并在完成后调用它。

考虑以下示例:

gulp.task('sign', function(done) {

  util.log(util.colors.yellow('fetching build number from remote URL:'));
  util.log(util.colors.yellow(JENKINS_URL));

  request(JENKINS_URL, function(err, res, body) {
    var parsed = isJson(body);
    var number = parsed.number;

    return gulp.src(path.join(DIST_DIR, '**'))
      .pipe(replace('<%= B =%>', number))
      .on('end', function() {
        util.log(util.colors.yellow('new build number is: ' + number));
      })
      .pipe(replace('<%= V =%>', VERSION))
      .on('end', function() {
        util.log(util.colors.yellow('app version is: ' + VERSION));
      })
      .pipe(gulp.dest(DIST_DIR))
      .on('finish', function() {
        util.log(util.colors.green('operation ended successfully!'));
        done(); 
      });
  });
});

通过这样做,当调用 done 函数时,您的任务将被视为已完成。

关于javascript - gulp 任务运行请求显示日志消息太晚了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41990730/

相关文章:

node.js - Docker-compose:npm install 成功后,node_modules 不存在于卷中

javascript - 需要用 gulp 延迟加载 ES6 模块

javascript - 无法在 Electron 中成功制作透明窗口(javascript)

javascript - 将 excel 转换为 json 数组时无法解析日期

javascript - 代码没有按顺序运行? DOM 的更新是一次性发生的吗?

node.js - 使用 Jasmine 进行单元测试时避免副作用

javascript - 使用多个独立的 gulp 文件构建不同的包

node.js - 如何在 TypeScript 中使用 gulp-load-plugins?

javascript - 如何重新实现 'var that = this' 以使用 Object.prototype.bind() 保存范围引用?

javascript - 为什么 "document.querySelector(' a.some class') [0].href"返回 null?