This.async () in the yomen generator

I am learning how to write a yeomen generator. I have a question regarding the code below. He says by adding var done = this.async(); and calling the method later in the callback, we can make the askFor() function an asynchronous function. Can someone 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 for this.async

 this.async = function() { return function() {}; } 
+6
source share
1 answer

It's just that a pure coincidence fell on this question, looking for something else.

In fact, this.async overwritten for each method during the run phase to delay execution until it completes or starts synchronously.

Here you can read the corresponding line of code: https://github.com/yeoman/generator/blob/master/lib/base.js#L372-L393

So basically, behind the scenes, Joiman always calls a callback. When you call this.async() , we save the reference variable and return the callback. If you do not name it, we will take care of calling the callback manually after the function finishes.

+8
source

Source: https://habr.com/ru/post/970045/


All Articles