[For ES6 Series -07] Generator Function: a function generator

[Original] code road workers Coder-Power

Hello everyone, here is the code the road workers have the power, I am yards road worker, you are the power.

github-pages
blog Park cnblogs


Generator function 生成器函数Is ES6the new syntactic sugar, in essence, is to package into a walker form, so that the encoding of control over the implementation of the program you get, layman's terms, the process control, kick kick, step, do not too violent ~

0. Introduction

Say to the generator function, you have to mention javascriptasynchronous evolution history programmatically.

(Not digress not digress not digress)

  • 1. Common mode callback function (callback)
  • 2. Event / Publisher - Subscriber Model (event / publisher - observer)
  • 3.Promise
  • 4.Generator
  • 5.async / await (formally proposed in ES8 / ES2017)

Which Promiseis a milestone solved when the callback function nested callback hellcallback hell problem (nested hierarchy too hard to read and maintain).

And the protagonist Generatoris more like syntax as a transition, at the launch async/awaitafter the basic rarely used.

async/await, CSharper turn the front, it looks like to see their loved ones, C#have the same syntax. (# Note: The addition of the C # 5.0)

Saying grammar evolution to really convenient ah. To separate articles in a rear Promiseand async/awaitopening paste.

1. Introduce yourself sentence

1.1 Talk is cheep, show you the CODE!

/* eg.0
 * Simple Example of Generator-Function
 */
//----------------------------------------

let songs = ["Hero", "Here I am", "The Show"]

// Generator-Function is Here Below:
function *play(songs) {
    for(let i=0; i<songs.length; i++) {
        yield songs[i]
    }
    // 这里可以有return
}

let g = play(songs)

let next = g.next()
console.log(next)   // { value: 'Hero', done: false }

next = g.next()
console.log(next)   // { value: 'Here I am', done: false }

next = g.next()
console.log(next)   // { value: 'The Show', done: false }

next = g.next()
console.log(next)   // { value: undefined, done: true }

//----------------------------------------

1.2 generator function definition

  • First, the function is defined to have a *symbol.

    *Either immediately functionbehind, it can also be attached to the front of the function name.

  • Second, there is a function within yieldthe keyword

    To interrupt processing, and can provide a return of foreign temporary value.

  • Other, no different from ordinary writing the function

About 1.3 using a generator function

  • 1. Like a normal function call, not get any specific return value, but an iterator. (It may also be viewed as a state machine)

  • 2. Try to kick. The iterator object obtained by calling the next()method, the start value to obtain a first object is returned.

  • 3. Keep kick. Call every next()method to get a result object, you can see the print information in the code above comments.

    Where the valuevalue that is currently available, donenamely the iterative state, it has only ture/falsetwo possibilities, when it becomes truethat the iteration is complete.

2. mainstream use

That is the normal way of using good practices it, should be fit promiseto use.

To a simple example:

/* eg.1
 * Simple Example of Generator-Function
 */
//----------------------------------------

function* func() {
    // 这里应该是ajax请求,结果是一个promise对象,简单模拟一下
    yield new Promise(function(resolve,reject){
        resolve('Hello')
    })
    
    // 这里应该是ajax请求,结果是一个promise对象,简单模拟一下
    yield new Promise(function(resolve,reject){
        resolve('World')
    })
}

let g = func()

g.next().value.then((data) => {
    console.log('log-1:', data)
    return g.next().value
}).then((data) => {
    console.log('log-2:', data)
})

// log-1: Hello
// log-2: World

//----------------------------------------

In this way, it will be asynchronous ajaxprocessing simply by writing out the way synchronization.

3. humble practice

In addition to handling asynchronous, yard workers personally feel that way, Generatormore suitable for use at the scene of the loop process. Wherein similar to the practice of this process, the following example:

/* eg.2 (part1)
 * My Example of Generator-Function
 */
//----------------------------------------
// 以下代码中都省略掉了检测处理

// 首先来一个Gernerator函数
function *getDateInPeriod(from, to, includEnd=false) {

    let fromDate = new Date(from)
    let toDate = new Date(to)

    if(includEnd) {
        toDate = addDays(toDate, 1)
    } 

    for(let date = fromDate;date < toDate; date=addDays(date, 1)) {
        yield date
    }
}

// 上面调用到了工具函数addDays
function addDays(date, days){
    date = new Date(date.setDate(date.getDate() + days))
    return date
}

//----------------------------------------

Then is the use, in the course of the cycle of value, there will be a number of business processes (synchronous or asynchronous).

/* eg.2 (part2)
 * My Example of Generator-Function
 */
//----------------------------------------

let arrDate = getDateInPeriod('2019-06-06', '2019-06-30', true)

let daysInPeriod = arrDate.next()

while(!daysInPeriod.done) {

    // 这里是一堆其它业务处理

    console.log(daysInperiod)

    daysInPeriod = arrDate.next()

}
console.log(daysInperiod)

//----------------------------------------

Print information results:

{ value: 2019-06-06T00:00:00.000Z, done: false }
{ value: 2019-06-07T00:00:00.000Z, done: false }
...
{ value: 2019-06-29T00:00:00.000Z, done: false }
{ value: 2019-06-30T00:00:00.000Z, done: false }
{ value: undefined, done: true }

In the above example, or synchronization. Maybe not a good use, but I can tell you this is a usage.

4. heard of the practice

The working code is not practiced, the effect that the Generatorfunction of the sugar in accordance with this syntax yieldcode into a plurality of portions, each person performs the manual control part, so the package an actuator function, to simplify the control process, so that asynchronous programming pleasant.

In fact, with async/awaitafter this really is not necessary.

( co.jsThat is, one such Generatorexecution library)

4. Other

In addition to the main use of a generator function described above, there are also other small point features, code and road workers did not practice, do not feel how will be used, there can be little understanding.

4.1 may be received by nexttransfer into parameters.

/* eg.3
 * parameters
 */
//----------------------------------------

function *genFunc(p) {
    console.log(`p is ${p}`)

    let p1 = yield p
    console.log(`p1 is ${p1}`)

    let p2 = yield p1
    console.log(`p2 is ${p2}`)
}


let gen = genFunc(1)
// 第一次next无法传参到Generator函数,应该由最初的函数调用处传递
gen.next(2)

// 从第二步next() 传的参数,在第一个yield处接收
gen.next(3)

About to yieldpass parameters does look a little bit strange, in fact, understand and not feel strange.

In the above description has been posted comments.

4.2 may have a default iterator

/* eg.4
 * get value by for-of loop
 */
//----------------------------------------

function *foo() {
    for(let i=0; i<6; i++) {
        yield i
    }
}

let gen = foo()

for(let item of gen) {
    console.log(item)
}

// 打印结果:
// 0
// 1
// 2
// 3
// 4
// 5
//----------------------------------------

to sum up

About generator function Generator Functionintroduced here now,

This is to be aware of the syntactic sugar on it, anyway, the future is not necessarily used to get really

Asynchronous processing is mainly used Promisewith async/await.

the above.

I hope you can help, you next time.

-END-


Guess you like

Origin www.cnblogs.com/CoderMonkie/p/ES6-Generator-Function.html