How can I promise-ify a one-off usage of gulp in my application?

这一生的挚爱 提交于 2019-11-30 18:19:01

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

Since the Gulp task is a stream, you can listen for its events:

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

  var stream = gulp.src(src + '/*.md')
    .pipe(marked({}))
    .pipe(gulp.dest(dist));

  stream.on('end', function() {
    def.resolve();
  });

  stream.on('error', function(err) {
    def.reject(err);
  });

  return def.promise;
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!