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

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

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)