問題描述
作為我正在編寫的一個小程序的一部分,我想使用 gulp 將大量文件轉(zhuǎn)換為 markdown.這不是獨立于程序的構(gòu)建步驟的一部分.這是程序的一部分.所以我沒有使用 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 任務(wù)完成時提醒我.
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
不接受回調(diào).我怎么能處理這個?感謝您的幫助,我對 gulp 有點陌生.
But pipe
doesn't take a callback. How could I handle this? Thanks for your help, I'm somewhat new to gulp.
推薦答案
gulp 中的一切都是一個流,所以你可以只監(jiān)聽 end
和 error
事件.
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 不再被開發(fā)(除了一些修復(fù))并且將完全不兼容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 及更高版本已內(nèi)置 ES6 承諾(不需要 --harmony
標(biāo)志),因此如果您不尋求向后兼容性,您可以使用它們來代替..
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);
});
};
這篇關(guān)于我如何保證在我的應(yīng)用程序中一次性使用 gulp?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!