20 Lines of Code Simple Implementation of Handwritten Async Await

If you were asked to hand-write the implementation of async functions, would you find it complicated? This article takes you to the core of it in 20 lines.

It is often said that the async function is the syntactic sugar of the generator function, so what kind of sugar is it? Let’s peel off its icing layer by layer.
Some students want to say, since the generator function is used, why implement async?
The purpose of this article is to take everyone to understand how async and generator work together to manage asynchrony.

https://medium.com/media/532b64285e26151c83768e3a6525608e/href

For this simple case, what would it look like if we expressed it as a generator function?

https://medium.com/media/d18120d8b2fa2d8000da4092b161b057/href

We know that the generator function will not be executed automatically. Every time its next method is called, it will stay at the next yield position.

Using this feature, we can make this generator function fully implement the function of async function as long as we write an automatically executed function.

https://medium.com/media/8da5629df2965c320c3b1a2a94fbc59c/href

So the general idea has been determined,

asyncToGenerator accepts a generator function and returns a promise,

The key lies in how the asynchronous process divided by yield should be automatically executed.

If Executed Manually

Before writing this function, we first simulate manually calling the generator function to complete the process step by step, which is helpful for later thinking.

https://medium.com/media/d3a85c2c32c425630df0e07ef63c1472/href

We first call testG to generate an iterator

var gen = testG()

Then start executing the first next

// The first time call next stays at the position of the first yield
// The returned promise contains the data required by data
var dataPromise = gen.next()

A promise is returned here, which is the promise returned by getData() for the first time. Note that:

const data = yield getData()

This code needs to be divided into two parts: the first call to next, but it actually just stays at yield getData(),
The value of data is not determined.
So when will the value of data be determined?
The next time you call next, the passed parameter will be used as the value accepted before the previous yield
That is to say, when we call gen.next again, the value of data will be determined as ‘this parameter will be assigned to the data variable’

gen.next('This parameter will be assigned to the data variable')
// Then the data here has value
const data = yield getData()
console.log('data: ', data);
// Then move on to the next yield
const data2 = yield getData()

Then execute down until the next yield is encountered, and continue this process…

This is a difficult point in the design of the generator function, but in order to achieve our goal, we still have to learn it~

With this feature, if we control the yield process in this way, can we achieve asynchronous serialization?

https://medium.com/media/33d27b07bb5ec90fbffe279184ad06ca/href

Such a call that looks like callback hell allows our generator function to arrange the asynchrony in a clear way.

With this in mind, it becomes easy to implement this higher-order function.

Let’s first look at the structure as a whole to get an impression, and then we’ll explain it line by line in comments.

https://medium.com/media/932f8e1c6e6b8dbf8441d0e1b2ac254b/href

No more, no less, 22 lines.

The next line by line explanation.

https://medium.com/media/f9fbb8ba1a82ca3341d48b82806d9480/href

Summarize

This article implements the asyncToGenerator function in the simplest way, which is the core of babel’s compilation of async functions. Of course, in babel, the generator function is also compiled into a very primitive form. In this article, we directly replace it with generator.
This is also a great pattern for implementing serialization of promises. if you are interested in my articles, you can follow me on Medium or Twitter.


20 Lines of Code Simple Implementation of Handwritten Async Await was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Maxwell

If you were asked to hand-write the implementation of async functions, would you find it complicated? This article takes you to the core of it in 20 lines.

It is often said that the async function is the syntactic sugar of the generator function, so what kind of sugar is it? Let’s peel off its icing layer by layer.
Some students want to say, since the generator function is used, why implement async?
The purpose of this article is to take everyone to understand how async and generator work together to manage asynchrony.

For this simple case, what would it look like if we expressed it as a generator function?

We know that the generator function will not be executed automatically. Every time its next method is called, it will stay at the next yield position.

Using this feature, we can make this generator function fully implement the function of async function as long as we write an automatically executed function.

So the general idea has been determined,

asyncToGenerator accepts a generator function and returns a promise,

The key lies in how the asynchronous process divided by yield should be automatically executed.

If Executed Manually

Before writing this function, we first simulate manually calling the generator function to complete the process step by step, which is helpful for later thinking.

We first call testG to generate an iterator

var gen = testG()

Then start executing the first next

// The first time call next stays at the position of the first yield
// The returned promise contains the data required by data
var dataPromise = gen.next()

A promise is returned here, which is the promise returned by getData() for the first time. Note that:

const data = yield getData()

This code needs to be divided into two parts: the first call to next, but it actually just stays at yield getData(),
The value of data is not determined.
So when will the value of data be determined?
The next time you call next, the passed parameter will be used as the value accepted before the previous yield
That is to say, when we call gen.next again, the value of data will be determined as ‘this parameter will be assigned to the data variable’

gen.next('This parameter will be assigned to the data variable')
// Then the data here has value
const data = yield getData()
console.log('data: ', data);
// Then move on to the next yield
const data2 = yield getData()

Then execute down until the next yield is encountered, and continue this process…

This is a difficult point in the design of the generator function, but in order to achieve our goal, we still have to learn it~

With this feature, if we control the yield process in this way, can we achieve asynchronous serialization?

Such a call that looks like callback hell allows our generator function to arrange the asynchrony in a clear way.

With this in mind, it becomes easy to implement this higher-order function.

Let’s first look at the structure as a whole to get an impression, and then we’ll explain it line by line in comments.

No more, no less, 22 lines.

The next line by line explanation.

Summarize

This article implements the asyncToGenerator function in the simplest way, which is the core of babel’s compilation of async functions. Of course, in babel, the generator function is also compiled into a very primitive form. In this article, we directly replace it with generator.
This is also a great pattern for implementing serialization of promises. if you are interested in my articles, you can follow me on Medium or Twitter.


20 Lines of Code Simple Implementation of Handwritten Async Await was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Maxwell


Print Share Comment Cite Upload Translate Updates
APA

Maxwell | Sciencx (2022-11-01T03:03:49+00:00) 20 Lines of Code Simple Implementation of Handwritten Async Await. Retrieved from https://www.scien.cx/2022/11/01/20-lines-of-code-simple-implementation-of-handwritten-async-await/

MLA
" » 20 Lines of Code Simple Implementation of Handwritten Async Await." Maxwell | Sciencx - Tuesday November 1, 2022, https://www.scien.cx/2022/11/01/20-lines-of-code-simple-implementation-of-handwritten-async-await/
HARVARD
Maxwell | Sciencx Tuesday November 1, 2022 » 20 Lines of Code Simple Implementation of Handwritten Async Await., viewed ,<https://www.scien.cx/2022/11/01/20-lines-of-code-simple-implementation-of-handwritten-async-await/>
VANCOUVER
Maxwell | Sciencx - » 20 Lines of Code Simple Implementation of Handwritten Async Await. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/11/01/20-lines-of-code-simple-implementation-of-handwritten-async-await/
CHICAGO
" » 20 Lines of Code Simple Implementation of Handwritten Async Await." Maxwell | Sciencx - Accessed . https://www.scien.cx/2022/11/01/20-lines-of-code-simple-implementation-of-handwritten-async-await/
IEEE
" » 20 Lines of Code Simple Implementation of Handwritten Async Await." Maxwell | Sciencx [Online]. Available: https://www.scien.cx/2022/11/01/20-lines-of-code-simple-implementation-of-handwritten-async-await/. [Accessed: ]
rf:citation
» 20 Lines of Code Simple Implementation of Handwritten Async Await | Maxwell | Sciencx | https://www.scien.cx/2022/11/01/20-lines-of-code-simple-implementation-of-handwritten-async-await/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.