如何在另一个中正确使用延迟gulp任务的返回值

时间:2016-05-05 18:37:15

标签: javascript node.js gulp

一个简单的例子:我有2个gulp任务(第二个需要从第一个得到的值),但是无法在第二个集合中获得值(在使用setTimeout执行第一个任务期间):

var gulp = require("gulp");

var values = undefined;

gulp.task("one", function(cb) {
    console.log(values);
    setTimeout(function() {
        console.log('First finnished!!!');
        values = "Vovan and Alex";
    }, 1000);
    cb(values);
})

gulp.task("two", ["one"], function() {
    console.log(values);
    console.log("Second's done!")

})

gulp.task("default", ["one", "two"]);

结果如下:

[18:24:26] Using gulpfile ~/workspace/gulpfile.js [18:24:26] Starting 'one'... undefined [18:24:26] Finished 'one' after 1.58 ms [18:24:26] Starting 'two'... undefined Second's done! [18:24:26] Finished 'two' after 302 μs [18:24:26] Starting 'default'... [18:24:26] Finished 'default' after 17 μs First finnished!!!

1 个答案:

答案 0 :(得分:0)

你通过调用cb来告诉我你的任务已经完成,这在你的例子中发生得太早了。如果将cb调用移至超时范围内,它将等待任务完成:

var gulp = require("gulp");

var values = undefined;

gulp.task("one", function(cb) {
    console.log(values);
    setTimeout(function() {
        console.log('First finnished!!!');
        values = "Vovan and Alex";
        cb(values);
    }, 1000);
})

gulp.task("two", ["one"], function() {
    console.log(values);
    console.log("Second's done!")

})

gulp.task("default", ["one", "two"]);

但是,您使用字符串数组调用cb并且gulp需要某种流。您可以将值写入共享变量,也可以创建包含数据的流以在任务之间传递。