this.async() in yeoman-generator

asynchronous, node.js, yeoman-generator

Solution

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.

Problem

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() {}; } ```

Original source