Home > Web Front-end > JS Tutorial > body text

Basic usage of ES6 Generator

Guanhui
Release: 2020-06-24 18:05:58
forward
2326 people have browsed it

Basic usage of ES6 Generator

The examples in this article describe the basic usage of ES6 Generator. Share it with everyone for your reference, the details are as follows:

1. Introduction to Generator

Let’s start with a basic code of Generator

function* g(){
 yield 100;
 yield 200;
 return 300;
}
let gg = g();
console.log(gg);            // Object [Generator] {}
console.log(gg.next());        // { value: 100, done: false }
console.log(gg.next());        // { value: 200, done: false }
console.log(gg.next());        // { value: 300, done: true }
console.log(gg.next());        // { value: undefined, done: true }
Copy after login

First we see:

  • Generator is defined by functinon*, and yield can be used inside the generator

  • Generator is not a function, but an object, and enters the paused state at the beginning of execution , instead of directly performing all operations

  • Use next() to perform the next operation, and the returns are all in the form {value: xxx, done: xxx}, and value represents the last time The value returned by the operation, done has two values, one is true and the other is false, indicating whether the entire process is completed.

2. Generator asynchronous programming

generator is an asynchronous solution introduced in ES6. Let’s take a look at its comparison with promise processing asynchronously to see their differences. .

// 这里模拟了一个异步操作
function asyncFunc(data) {
 return new Promise( resolve => {
  setTimeout(
   function() {
    resolve(data)
   },1000
  )
 })
}
Copy after login

Promise processing method:

asyncFunc("abc").then( res => {
 console.log(res);                    // "abc"
 return asyncFunc("def")
}).then( res => {
 console.log(res);                    // "def"
 return asyncFunc("ghi")
}).then( res => {
 console.log(res);                    // "ghi"
})
Copy after login

generator processing method:

function* g() {
 const r1 = yield asyncFunc("abc");
 console.log(r1);                            // "abc"
 const r2 = yield asyncFunc("def");
 console.log(r2);                            // "def"
 const r3 = yield asyncFunc("ghi");
 console.log(r3);                            // "ghi"
}

let gg = g();
let r1 = gg.next();
r1.value.then(res => {
 let r2 = gg.next(res);
 r2.value.then(res => {
  let r3 = gg.next(res);
  r3.value.then(res => {
   gg.next(res)
  })
 })
})
Copy after login

Promise multiple callbacks appear to be more complicated, and the code is not concise enough. The generator looks at the asynchronous processing The seemingly synchronous code is actually an asynchronous operation. The only thing is that the processing is relatively complicated. If only one asynchronous operation is performed, a generator is more suitable.

3.yield and yield*

Let’s look at two pieces of code first

function* g1() {
 yield 100;
 yield g2();
 return 400;
}

function* g2() {
 yield 200;
 yield 300;
}

let gg = g1();
console.log(gg.next());                // { value: 100, done: false }
console.log(gg.next());                // { value: Object [Generator] {}, done: false }
console.log(gg.next());                // { value: 400, done: true }
console.log(gg.next());                // { value: undefined, done: true }
Copy after login
function* g1() {
 yield 100;
 yield* g2();
 return 400;
}

function* g2() {
 yield 200;
 yield 300;
}

let gg = g1();
console.log(gg.next());                // { value: 100, done: false }
console.log(gg.next());                // { value: 200, done: false }
console.log(gg.next());                // { value: 300, done: false }
console.log(gg.next());                // { value: 400, done: true }
Copy after login

yield will not traverse another generator, and returns an iterator object, while yield *The generator will be traversed and iterated.

Recommended tutorial: "JS Tutorial"

The above is the detailed content of Basic usage of ES6 Generator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
es6
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template