Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【入门1-4】认识es6中的generator #4

Open
yaogengzhu opened this issue Feb 25, 2020 · 1 comment
Open

【入门1-4】认识es6中的generator #4

yaogengzhu opened this issue Feb 25, 2020 · 1 comment
Labels
ES6 Extra attention is needed

Comments

@yaogengzhu
Copy link
Owner

generator

了解generator

// 生成器和迭代器

/**
 *  理解koa基础,异步解决方案, async await 的基础
 */

 /**
  * 
  *  read 生存器
  */

 function read(books){ 
    let index = 0
    console.log(index)
    return {
        next() {
            // 只要没取到就为false, 取不到为true
            let done = index == books.length - 1 
            let value = done ? undefined : books[index++]
            return {
                value,
                done
            }
        }
    }
 }


 // 迭代器可以不停的调用next 方法得到一个结果 { value, done}
 // done 为true时取完
 let it = read(['js', 'node'])
 // it 有一个next ,每次调用next 会返回一个结果 { value, done}
 let r1 = it.next()
 console.log(it)
 let r2 = it.next()
 console.log(r1)
 console.log(r2)


 /**
  *   生成器函数 和 普通函数不一样。 返回迭代器
  *   执行的时候也不一样
  */

  function *listen(books) {
    console.log('开始')
    for( let i =0; i < books.length; i++) {
        // yield  放弃屈服
        yield books[i]
    }
  }

  let  it1 = listen(['js', 'node'])
  let r3 = it1.next()
  let r4 = it1.next()
  let r5 = it1.next()

console.log(r3)
console.log(r4)
console.log(r5)
@yaogengzhu yaogengzhu added the ES6 Extra attention is needed label Feb 25, 2020
@yaogengzhu
Copy link
Owner Author

/**
 * 生成器是一个函数, 可以用来生成迭代器
 * 生成器和普通函数不一样, 普通函数一旦执行,就必须执行完毕
 * 生成器函数可以暂停
 */

/**
 *  生成器函数遇到暂停点就会停下来,直到再次让他执行
 */

/**
 * 
 */

// 生成器函数和普通函数不一样, 调用它的话函数并不会立即执行
// 它会返回一个生成器的迭代器,迭代器是一个对象,每调用next() 就会执行一次
function* go() {
    console.log(1)
    // 此处的b 是供外界输入进来的值
    // 这行代码实现了输入和输出, 本次的输出放入yield的后面,下次的输入放在yield的前面
    let b = yield true

    console.log(2)
    let c = yield b

    console.log(3)
    // let d = yield c
    return c
}

let it = go()

// r1.next()
let r1 = it.next('A值')
// 第一次调用next,会返回一个对象,第一个值value是 yield 'a', 第二个值是 done 表示迭代是否完成
// next 第一次执行传递参数是没有意义的
console.log(r1)
let r2 = it.next('B值')
console.log(r2)
let r3 = it.next('c值')
console.log(r3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ES6 Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant