I am learning how to write a yeoman-generator. I have a question regarding the code below. It says by adding var done = this.async();
and call the method later in callback, we can make the function askFor()
a asynchronized function. Could someone please explain why?
askFor: function() {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay('Welcome to the marvelous Myblog generator!'));
var prompts = [{
name: 'blogName',
message: 'What do you want to call your blog?',
default: 'myblog'
}];
this.prompt(prompts, function(props) {
this.blogName = props.blogName;
done();
}.bind(this));
}
Here is the code of this.async
this.async = function() {
return function() {};
}
Just fell on this question by pure coincidence searching for something else.
Actually, this.async
is overwritten on each method during the run
phase to either delay execution until completion or run synchronously.
You can read the relevant code line here: https://github.com/yeoman/generator/blob/master/lib/base.js#L372-L393
So basically, behind the scenes Yeoman always call a callback. When you call this.async()
we keep a reference variable and return the callback. If you don't call it, we take care of calling the callback manually after the function end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With