klei/gulp-inject

Multi injection, seems asynchronous

brucejcw opened this issue · 5 comments

I have an array nodes, and each node.url refer to a html, then it will be injected into template.html
So I write a loop function to do it, but seems the log "finish" will print early before the loop done.
and task html will start before inject log print finish, is that means the inject action is doing asynchronous, and task html not wait for inject finish?

BTW, is there a better way to write this batch inject?

gulp.task('html', ['inject'], () => {

})

gulp.task('inject', ()=>{
    var gen = function(node) {
        gulp.src('./templates/template.html')
            .pipe($.replace(/@name@/, node.name))
            .pipe($.replace(/@nav@/, node.nav))
            .pipe($.inject(es.merge(bowers, extraLib), {
                name: 'bower'
            }))
            .pipe($.inject(styles))
            .pipe($.inject(js))
            .pipe($.inject(header, {
                starttag: '<!-- inject:header:html -->',
                transform: function(filePath, file) {
                    return file.contents.toString('utf8')
                }
            }))
            .pipe($.inject(footer, {
                starttag: '<!-- inject:footer:html -->',
                transform: function(filePath, file) {
                    return file.contents.toString('utf8')
                }
            }))
            .pipe($.inject(gulp.src(path.join(conf.paths.tmp, node.url)), {
                starttag: '<!-- inject:html-body:html -->',
                transform: function(filePath, file) {
                    return file.contents.toString('utf8')
                }
            }))
            .pipe($.rename(node.url))
            .pipe(gulp.dest(path.join(conf.paths.tmp, '/serve')))
            .pipe($.size({
                title: path.join(conf.paths.tmp, '/serve'),
                showFiles: true
            }));
    }

    loop(nodes);

    function loop(nodes) {
        forEach(nodes, (node) => {
            gen(node);
        })
    }
    console.log('finish')

    ...
})

2015-11-24 17 08 44

Is there a workaround for this?

+1

AFAIK you should return a gulp stream in your task or use a callback to let the calling task know when the subtask is done. See here.

See this comment for a solution for this.

Thanks