我该如何承诺 - 如果在我的应用程序中使用一次性使用gulp? [英] How can I promise-ify a one-off usage of gulp in my application?

查看:136
本文介绍了我该如何承诺 - 如果在我的应用程序中使用一次性使用gulp?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我正在编写的一个小程序的一部分,我想使用gulp将大量文件转换为降价。这不是与程序分开的构建步骤的一部分。这是该计划的一部分。所以我没有使用gulpfile来处理这个问题。



问题在于,由于它是异步的,我想使用一个承诺,在吞吐任务完成时会提醒我。



类似这样的东西将会是理想的:

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

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

return def.promise;

但是 pipe doesn没有回调。我怎么能处理这个?感谢您的帮助,我有点新的吞噬。

解决方案

gulp中的所有内容都是流,因此您可以只听 end 和 error events。

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

另外, Q 1.0 不再开发(除了在这里和那里的一些修复),并且将与Q 2.0完全不兼容;我建议使用 Bluebird 作为替代方案。

另外值得一提的是,NodeJS 0.12以上版本内置了ES6承诺(不需要 - harmony 标志)如果你不想向后兼容,你可以直接使用它们。

  io.convertSrc = function(){
返回新的Promise(函数(resolve,reject){
gulp.src(src +'/*.md')
.pipe(标记为{{}))
.pipe (gulp.dest(dist))
.on('end',resolve)
.on('error',reject);
});
};


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.

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

Something like this would be ideal:

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

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

解决方案

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

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.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆