pedalpete
pedalpete

Reputation: 21536

chaining gulp tasks and passing variables

I'm trying to build up a gulp task which sorts my javascript files into the proper order before concatenating them.

This means 1-> get the installed bower components, 2-> sort the components into the include order, 3-> pass the sorted array of files to the concat method.

So far, I've managed this

var gulp = require('gulp');
var dependency_orderer = require('dependency-orderer');
var exec = require('child_process').exec;

var bower_list, depend_array, js_depend_array;
gulp.task('order-dependencies',['get-bower-list'], function(){
    console.log(bower_list);
 //   depend_array = dependency_orderer(bower_list);
    //console.log(depend_array);
//    return depend_array;
});

gulp.task('get-bower-list', function(){
    exec('bower list -p', function(err, stdout, stderr){
        if(err) return console.log(err);
        bower_list = stdout;
        console.log(bower_list);
        return bower_list;
    });

});
gulp.task('concat-files',['order-dependencies'], function(){


});

But the problem is that I can't seem to get my bower_list in the order-dependencies task.

Any suggestions on how to accomplish this?

Upvotes: 2

Views: 3103

Answers (1)

AntouanK
AntouanK

Reputation: 4968

Your problem is that the task finishes without waiting for the async call you make ( the exec(...) ). So the variable is still undefined when you read it in the 2nd task.

Try using the callback to define when your task ends

gulp.task('get-bower-list', function(done){
    exec('bower list -p', function(err, stdout, stderr){
        if(err) return console.log(err);
        bower_list = stdout;
        console.log(bower_list);
        return done();
    });
});

and you can also use promises to define when tasks are 'done'

see the API docs

Upvotes: 3

Related Questions