- Javascript – generator-yield /Next & async-await
- Deepak Gupta
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: iceytea
- Proofreader: Huimingwu, Zsky
Generator (ES6)
A generator function is a function that returns multiple values at different intervals as required by the user and manages its internal state. If a function uses the function* syntax, it becomes a generator function.
They differ from normal functions, which run in a single execution, whereas Generator functions can be paused and resumed. They do run, but the trigger is in our hands. They give asynchronous functions better execution control, but that doesn’t mean they can’t be used as synchronous functions.
Note: When the generator function is executed, a new generator object is returned.
Pausing and resuming the generator is done using yield and next. Let’s take a look at what they are and what they can do.
Yield/Next
The yield keyword suspends the execution of the generator function, and the value of the expression following the yield keyword is returned to the caller of the generator. It can be understood as the return keyword based on the generator version.
The yield keyword actually returns an IteratorResult object with both value and done attributes. (If you don’t know what iterators and iterables are, click here.)
Once the yield expression is paused, code execution of the Generator remains paused until generator’s next() method is called. Each time generator’s next() method is called, the generator resumes execution and returns the iterator result.
HMM… Let’s take a look at an example:
function* UUIDGenerator() {
let d, r;
while(true) {
yield 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g.function(c) {
r = (new Date().getTime() + Math.random()*16) %16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16); }); }};Copy the code
UUIDGenerator is a generator function that calculates the UUID using the current time and random number and returns a new UUID each time it is executed.
To run the above function, we need to create a generator object that calls next() :
const UUID = UUIDGenerator();
// UUID is our generator object
UUID.next()
// return {value: 'e35834ae-8694-4e16-8352-6d2368b3ccbf', done: false}
Copy the code
Each time uuID.next () returns the value of the new UUID, the done value will always be false because we are in an infinite loop.
Note: We paused on an infinite loop, which is a cool way to do it. At any “stop point” in a generator function, you can not only generate values for external functions, but also receive values from external functions.
There are many implementations of generator, and many libraries are in heavy use. Examples include CO, KOA and Redux-Saga.
Async/Await (ES7)
By convention, when an asynchronous operation returns data processed by a Promise, the callback is passed and invoked.
Async/Await is a special syntax that uses promises in a more comfortable way that is very easy to understand and use.
The Async keyword is used to define an asynchronous function that returns an AsyncFunction object.
The Await keyword is used to suspend asynchronous function execution until the Promise is resolved (resolved or Rejected) and continue async function execution after completion. When restored, the value of the await expression is the value of the implemented Promise.
Key points:
- Await can only be used in asynchronous functions.
- Functions with the async keyword will always return promises.
- Multiple await statements under the same function will always run in order.
- If a promise is resolved normally, then
await
Returns thepromise
The results. But if it’s rejected, it throws an error, just like it does in that linethrow
Same statement.- Asynchronous functions cannot wait for more than one promise at a time.
- If you use await more than once after await, and the latter statement does not depend on the previous statement, performance problems may occur.
So far so good, let’s look at a simple example:
async function asyncFunction() {
const promise = new Promise((resolve, reject) = > {
setTimeout((a)= > resolve("i am resolved!"), 1000)});const result = await promise;
// wait till the promise resolves (*)
console.log(result); // "i am resolved!"
}
asyncFunction();
Copy the code
On the await Promise line, asyncFunction performs “pause” and replies when the promise is resolved, and result (const result on line 95) becomes its result. The code above says “I am Resolved!” after a second. .
Compare Generator and async-await
- Both the Generator /yield and Async /await functions can be used to write asynchronous code that “waits”, which means that the code looks synchronous even if it is asynchronous.
- The Generator functionIn accordance with theYield and yieldThat is, a yield expression is executed once through an iterator
next
Methods), whileAsync-awaitIn accordance with theAwait then awaitIs executed in order. - Async/await makes it easier to implement specific use cases for Generators.
- The return value of Generator is always {value: X, done: Boolean}. For Async functions it will always be a promise that resolves to the value X or throws an error.
- Async functions can be implemented by splitting them into generators and promises, which are useful.
If you’d like to be added to my email list, please consider entering your email here, and follow me on Medium to read more javascript articles, and check out my crazy code on Github. If anything isn’t clear, or if you’d like to point something out, please comment below.
You may also like my other posts:
- Nodejs app structure
- Javascript data structure with map, reduce, filter
- Javascript- Currying VS Partial Application
- Javascript ES6 — Iterables and Iterators
- Javascript Performance test – for vs for each VS (Map, Reduce, filter, find)
- Javascript — Proxy
Clap your hands if you enjoyed this article. Hint: You can take 50 shots! Also, recommendations and shares are welcome to help others find it!
Thank you very much!
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.