2015-04-17 40 views
12

只是一个简单的问题来澄清吞咽任务中参数"done"的作用是什么?Gulp“完成”方法做什么?

我明白了,这是任务函数的回调函数,如下所示。

gulp.task('clean', function(done) { 
    // so some stuff 
    creategulptask(cleantask(), done); 
}); 

但是通过它的原因是什么?

回答

20

吞气文档指定类似下面的东西:

var gulp = require('gulp'); 

// Takes in a callback so the engine knows when it'll be done 
// This callback is passed in by Gulp - they are not arguments/parameters 
// for your task. 
gulp.task('one', function(cb) { 
    // Do stuff -- async or otherwise 
    // If err is not null and not undefined, then this task will stop, 
    // and note that it failed 
    cb(err); 
}); 

// Identifies a dependent task must be complete before this one begins 
gulp.task('two', ['one'], function() { 
    // Task 'one' is done now, this will now run... 
}); 

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

的进行参数传递到您用于定义任务的回调函数。

您的任务函数可以“接受回调”函数参数(通常此函数参数名为done)。执行done函数告诉Gulp“任务完成时提示它”。如果您想订购的是互相依赖,如在上面的例子中的任务一系列

咕嘟咕嘟需要这个提示。 (即任务two将不会开始,直到任务one调用cb())实质上,如果您不想让它们同时运行,那么它将停止并发运行任务。

您可以在这里阅读更多关于此:https://github.com/gulpjs/gulp/blob/master/docs/API.md#async-task-support

+1

很好解释。谢谢@Seer – Nexus23

+2

只是好奇,如果我给他的函数有一个参数或者没有参数,那么gulp如何检查和知道?这在Javascript中如何实现?这听起来像反思。 –

+0

如果您需要在任务内运行异步进程,而您希望任务等待完成,那么在返回之前,回调特别有用。否则,只需返回流就足够了。另请参阅https://github.com/gulpjs/gulp/blob/master/docs/API.md#async-task-support – grtjn

-3

done参数不是回调,匿名function是回调。 done只是一个参数,你可以传递到你的回调方法出于任何原因。

一饮而尽任务是typically defined as

gulp.task('somename', function() { 
    // Do stuff 
}); 

你可以定义任务中执行什么样的代码的功能。如果此代码是依赖于任何参数,你可以将它们作为函数的参数:

gulp.task('birthdayTask', function(name, dateOfBirth) { 
    doFancyStuff(name, dateOfBirth); 
}); 

在你的情况,done可能是因为cleantask()方法完成被尽快执行另一个回调。因此,当cleantask完成时,它将充当某种通知机制。但是,这不能从您的代码中派生出来,因为您没有提供cleantask()函数的代码,所以只需在此猜测。

+0

明白了。它与ajax中的异步机制相同吗? – Nexus23

+3

这是不正确的。你不能像这样将参数传递给gulp任务,你必须使用可用的许多参数处理器之一。看到我的答案。 – Seer

+1

至少使用[gulp-param](https://github.com/stoeffel/gulp-param)插件可以将参数传递给gulp任务。我一直在做。尽管如此,你也许是对的。我很抱歉。 – user1438038

相关问题