简体   繁体   English

node.js流中的控制流

[英]Control flow in node.js streams

I'm writing a gulp.js task, that concats/uglify my javascripts into app.min.js, then when it finishes, I want to inject app.min.js into a script tag in my index.jade file. 我正在写一个gulp.js任务,将我的JavaScript合并/丑化到app.min.js中,然后在完成时,我想将app.min.js注入index.jade文件中的脚本标签中。

So I was writing the next task, without really knowing how node.js control flow works... (I'm better with promises). 所以我在写下一个任务时,并没有真正知道node.js的控制流程是如何工作的……(我对诺言更好)。

gulp.task('js-prod', function () {
return gulp.src(['js/main.js', 'js/**/*.js', 'dist/templates.js', '!js/**/*.spec.js'])
    .pipe(sourcemaps.init())
    .pipe(concat('app.min.js'))
    .pipe(gulp.dest('dist'))
    .pipe(ngAnnotate())
    .pipe(uglify({mangle: false}))
    .pipe(rename('app.min.js'))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist'))
    .on('end', function () {
        var target = gulp.src('./index.jade');
        var sources = gulp.src(['dist/app.min.js'], {read: false});
        return target.pipe(inject(sources)).pipe(gulp.dest('./'));
    });

}); });

It seems to work, but is it the right way? 看来可行,但这是正确的方法吗? Will gulp.js take the right async-hint? gulp.js会采用正确的异步提示吗? the one from the 'end' event? 来自“结束”事件的那一个? Im promises it will be --> 我保证会->

return startBuildPromise().then(function(){return (injectFileScript()});

Try this: 尝试这个:

gulp.task('js-prod', function (cb) {
    gulp.src(['js/main.js', 'js/**/*.js', 'dist/templates.js', '!js/**/*.spec.js'])
        .pipe(sourcemaps.init())
        .pipe(concat('app.min.js'))
        .pipe(gulp.dest('dist'))
        .pipe(ngAnnotate())
        .pipe(uglify({mangle: false}))
        .pipe(rename('app.min.js'))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('dist'))
        .on('end', function () {
            var target = gulp.src('./index.jade');
            var sources = gulp.src(['dist/app.min.js'], {read: false});
            target.pipe(inject(sources))
                .pipe(gulp.dest('./'))
                on('end', cb);
        });
    });
});

Note that gulp will run as soon as the on('end') event happens. 请注意,gulp将在on('end')事件发生后立即运行。 Now we have an unclear scenario as two things are listening to on('end'). 现在我们有一个不清楚的场景,因为有两件事正在监听on('end')。 Should the target.pipe(inject).pipe(dest) run first or gulp's "start up the next task"? 应该首先运行target.pipe(inject).pipe(dest)还是gulp的“启动下一个任务”? Using callbacks makes this more explicit, and thus easier to reason about. 使用回调使此操作更明确,从而更易于推理。 If ever you're unsure which comes first, use a callback ... and ensure you return nothing. 如果您不确定哪一个先出现,请使用回调...并确保不返回任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM