我如何保证在我的应用程序中一次性使用 gulp?

How can I promise-ify a one-off usage of gulp in my application?(我如何保证在我的应用程序中一次性使用 gulp?)
本文介绍了我如何保证在我的应用程序中一次性使用 gulp?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

作为我正在编写的一个小程序的一部分,我想使用 gulp 将大量文件转换为 markdown.这不是独立于程序的构建步骤的一部分.这是程序的一部分.所以我没有使用 gulpfile 来处理这个问题.

As part of a small program I'm writing, I would like to use gulp to convert a large set of a files to markdown. This is not part of a build step separate from the program. It's a part of the program. So I'm not using a gulpfile to handle this.

问题是,因为它是异步的,所以我想使用一个 Promise,它会在 gulp 任务完成时提醒我.

The problem is, since it's async, I want to use a promise which will alert me when the gulp task is finished.

这样的东西是理想的:

io.convertSrc = function() {
  var def = q.defer();

  gulp.src(src + '/*.md')
    .pipe(marked({}))
    .pipe(gulp.dest(dist), function() {
      def.resolve('We are done!');
    });

    return def.promise;
}

pipe 不接受回调.我怎么能处理这个?感谢您的帮助,我对 gulp 有点陌生.

But pipe doesn't take a callback. How could I handle this? Thanks for your help, I'm somewhat new to gulp.

推荐答案

gulp 中的一切都是一个流,所以你可以只监听 enderror 事件.

Everything in gulp is a stream, so you can just listen for the end and error events.

io.convertSrc = function() {
  var def = q.defer();
  gulp.src(src + '/*.md')
    .pipe(marked({}))
    .pipe(gulp.dest(dist))
    .on('end', function() {
      def.resolve();
    })
    .on('error', def.reject);
  return def.promise;
}

顺便说一句,Q 1.0 不再被开发(除了一些修复)并且将完全不兼容Q 2.0;我推荐 Bluebird 作为替代方案.

As an aside, Q 1.0 is no longer developed (aside from a few fixes here and there) and will be wholly incompatible with Q 2.0; I'd recommend Bluebird as an alternative.

还值得一提的是,NodeJS 0.12 及更高版本已内置 ES6 承诺(不需要 --harmony 标志),因此如果您不寻求向后兼容性,您可以使用它们来代替..

Also worth mentioning that NodeJS 0.12 onwards has ES6 promises built into it (no --harmony flag necessary) so if you're not looking for backwards compatibility you can just use them instead..

io.convertSrc = function() {
  return new Promise(function(resolve, reject) {
    gulp.src(src + '/*.md')
      .pipe(marked({}))
      .pipe(gulp.dest(dist))
      .on('end', resolve)
      .on('error', reject);
  });
};

这篇关于我如何保证在我的应用程序中一次性使用 gulp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I can get a text of all the cells of the table using testcafe(如何使用 testcafe 获取表格中所有单元格的文本)
node_modules is not recognized as an internal or external command(node_modules 未被识别为内部或外部命令)
How can I create conditional test cases using Protractor?(如何使用 Protractor 创建条件测试用例?)
PhantomJS and clicking a form button(PhantomJS 并单击表单按钮)
Clicking #39;OK#39; on alert or confirm dialog through jquery/javascript?(在警报上单击“确定或通过 jquery/javascript 确认对话框?)
QunitJS-Tests don#39;t start: PhantomJS timed out, possibly due to a missing QUnit start() call(QunitJS-Tests 不启动:PhantomJS 超时,可能是由于缺少 QUnit start() 调用)