Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.async() in yeoman-generator

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() {};
}
like image 955
Benson Avatar asked May 29 '14 17:05

Benson


1 Answers

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.

like image 175
Simon Boudrias Avatar answered Sep 27 '22 18:09

Simon Boudrias