this.async() in yeoman-generator
Asked Answered
P

1

6

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() {};
}
Parentage answered 29/5, 2014 at 17:1 Comment(2)
Do you already understand the difference between synchronous and asynchronous javascript?Interlunar
Yes, I do understand the difference. But I don't understand how it makes the code asynchronous here by using this.async()Parentage
L
8

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.

Logistics answered 10/8, 2014 at 20:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.