![](/img/trans.png)
[英]I am trying to transfer the value from one task to another from callback with gulp 4, but have error
[英]How to properly use returned value from delayed gulp task in another one
一個簡單的例子:我有 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!!!
您通過調用cb
告訴 gulp 您的任務已完成,這在您的示例中發生得太快了。 如果在超時內移動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 需要某種流。 您可以將值寫入共享變量或使用數據創建流以在任務之間傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.