admin管理员组文章数量:1384214
For example, I read Grunt documentation on Creating Tasks. In "Tasks can be asynchronous" section, there is a use case of "done" function, I wonder why do we need that.
grunt.registerTask('asyncfoo', 'My "asyncfoo" task.', function() {
// Force task into async mode and grab a handle to the "done" function.
var done = this.async();
// Run some sync stuff.
grunt.log.writeln('Processing task...');
// And some async stuff.
setTimeout(function() {
grunt.log.writeln('All done!');
done();
}, 1000);
});
For example, I read Grunt documentation on Creating Tasks. In "Tasks can be asynchronous" section, there is a use case of "done" function, I wonder why do we need that.
grunt.registerTask('asyncfoo', 'My "asyncfoo" task.', function() {
// Force task into async mode and grab a handle to the "done" function.
var done = this.async();
// Run some sync stuff.
grunt.log.writeln('Processing task...');
// And some async stuff.
setTimeout(function() {
grunt.log.writeln('All done!');
done();
}, 1000);
});
Share
Improve this question
edited Jul 24, 2015 at 7:53
philomath
asked Jul 24, 2015 at 7:09
philomathphilomath
2,2096 gold badges34 silver badges46 bronze badges
1
- It's a callback to say the task is done, if a task is async it needs the callback to know when it's done (and if is fails or not) – michelem Commented Jul 24, 2015 at 7:22
2 Answers
Reset to default 3It's the only way for Grunt to know when your task is plete when doing async work.
This SO Post provides quite a bit of detail of what async in JS means and how to work with it.
Basically, setTimeout
calls your callback function 1 second later. However, grunt has no idea when your callback is plete, as setTimeout
itself returns immediately once it is called. Therefore, the done()
function exists to provide you a way to tell grunt that your task is plete, whenever that may be.
Grunt internally has a flag that determines if a task should be marked as plete when the task-function finishes or if it should be handled asynchronously. By default Grunt runs tasks synchronously and the this.async()
call toggles this flag.
The "synchronous-by-default" design decision was probably made to make simple tasks easier to write where you could use fs.writeSync etc., which is definitely a valid approach albeit gets in the way with at least the kind of tasks that I usually write nowadays.
Grunt was also created before Promises became a viable solution for callback-hells, so there's that too.
I'm pretty sure there are also other reasons for this that I'm not aware of :)
本文标签: quotDonequot function in javascriptStack Overflow
版权声明:本文标题:"Done" function in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744535121a2611266.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论