如何在 Gulp `.pipe` 中执行自定义异步操作?
How to execute custom asynchronous manipulations inside Gulp `.pipe`?
gulp-intercept 允许对文件进行同步操作:
import gulpIntercept from "gulp-intercept";
import VinylFile from "vinyl";
// ...
.pipe(gulpIntercept((compiledHtmlFile: VinylFile): VinylFile => {
doSomethingSyncWith(compiledHtmlFile)
return compiledHtmlFile;
}))
// ...
但我不确定它是否适用于异步操作,因为它还没有被记录下来。好吧,在开发这个包的时候,也许 ECMAScript 中甚至连 Promise 都不存在。
import gulpIntercept from "gulp-intercept";
import VinylFile from "vinyl";
// ...
// I suppose it will not work.
.pipe(gulpIntercept(async (compiledHtmlFile: VinylFile): VinylFile => {
// does "gulp.pipe" really will wait until it ends?
await doSomethingAsyncWith(compiledHtmlFile)
return compiledHtmlFile;
}))
// ...
应该有另一个 gulp 插件来代替异步操作。可以教教我吗?
看起来您正在使用的库不支持异步函数作为输入(正如您已经说过的!)但您根本不需要使用该库,您可以使用 event-stream
和 map
您的函数并在末尾按以下方式调用 callback
:
import VinylFile from "vinyl";
const es = require('event-stream');
const gulp = require('gulp');
// ..
.pipe(
es.map(
async (compiledHtmlFile: VinylFile, callback: any): VinylFile => {
// "gulp.pipe" will really wait until it ends!!!
await doSomethingAsyncWith(compiledHtmlFile);
callback(null, compiledHtmlFile);
}
)
)
// ...
或与一起使用然后:
// ..
.pipe(
es.map(
async (compiledHtmlFile: VinylFile, callback: any): VinylFile => {
doSomethingAsyncWith(compiledHtmlFile)
.then(() => {
callback(null, compiledHtmlFile);
});
}
)
)
// ...
gulp-intercept 允许对文件进行同步操作:
import gulpIntercept from "gulp-intercept";
import VinylFile from "vinyl";
// ...
.pipe(gulpIntercept((compiledHtmlFile: VinylFile): VinylFile => {
doSomethingSyncWith(compiledHtmlFile)
return compiledHtmlFile;
}))
// ...
但我不确定它是否适用于异步操作,因为它还没有被记录下来。好吧,在开发这个包的时候,也许 ECMAScript 中甚至连 Promise 都不存在。
import gulpIntercept from "gulp-intercept";
import VinylFile from "vinyl";
// ...
// I suppose it will not work.
.pipe(gulpIntercept(async (compiledHtmlFile: VinylFile): VinylFile => {
// does "gulp.pipe" really will wait until it ends?
await doSomethingAsyncWith(compiledHtmlFile)
return compiledHtmlFile;
}))
// ...
应该有另一个 gulp 插件来代替异步操作。可以教教我吗?
看起来您正在使用的库不支持异步函数作为输入(正如您已经说过的!)但您根本不需要使用该库,您可以使用 event-stream
和 map
您的函数并在末尾按以下方式调用 callback
:
import VinylFile from "vinyl";
const es = require('event-stream');
const gulp = require('gulp');
// ..
.pipe(
es.map(
async (compiledHtmlFile: VinylFile, callback: any): VinylFile => {
// "gulp.pipe" will really wait until it ends!!!
await doSomethingAsyncWith(compiledHtmlFile);
callback(null, compiledHtmlFile);
}
)
)
// ...
或与一起使用然后:
// ..
.pipe(
es.map(
async (compiledHtmlFile: VinylFile, callback: any): VinylFile => {
doSomethingAsyncWith(compiledHtmlFile)
.then(() => {
callback(null, compiledHtmlFile);
});
}
)
)
// ...