在继续下一个任务之前,让gulp同步写入文件

aso*_*erg 16 javascript node.js gulp

gulpfile.js

gulp.task('browser-bundle', ['react'], function() {
...

});


gulp.task('react', function(){
  gulp.src(options.JSX_SOURCE)
      .pipe(react())
      .pipe(gulp.dest(options.JSX_DEST))
});
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我具有浏览器捆绑任务,具体取决于响应任务.我相信这是按预期工作的,因为在输出中我看到了这个:

[gulp] Running 'react'...
[gulp] Finished 'react' in 3.43 ms
[gulp] Running 'browser-bundle'...
Run Code Online (Sandbox Code Playgroud)

但是,虽然响应任务已完成,但它应该写入操作系统的文件还没有完成.我注意到,如果我在浏览器bundle命令中放入一个sleep语句,那么它会按预期工作,但这对我来说似乎有点笨拙.

如果我希望在将文件(来自gulp.dest)同步写入磁盘之前不认为react任务已完成,我该怎么做?

RWA*_*WAM 29

你需要一个return语句:

gulp.task('react', function(){
    return gulp.src(options.JSX_SOURCE)
        .pipe(react())
        .pipe(gulp.dest(options.JSX_DEST))
});
Run Code Online (Sandbox Code Playgroud)

这样我的所有写操作都在下一个任务处理之前完成.


per*_*mon 5

回到2019年:如果有人来到这里遇到类似的问题

至少在 gulp 4.* 中,gulp 等待 Promise 解析但忽略结果。所以...如果您使用异步等待模式并返回结果,gulp.src('...')您会得到一个惊喜。该任务不会等待流完成才继续!这可能会导致严重的错误和时间浪费。解决方案是"promisify" gulp.src

例子:


gulp.task( async function notWaitingTask(){
   // the return stream are ignored because function return promise not stream
   return gulp.src('file.js')
     .pipe(gulp.dest('new-location'))

})

gulp.task( async function waitingTask(){
   // the return stream are respect

   await promisifyStream(
     gulp.src('file.js')
      .pipe(gulp.dest('new-location'))
   )

})

function promisifyStream(stream) {
    return new Promise( res => stream.on('end',res));
}


Run Code Online (Sandbox Code Playgroud)