• Iterator-Generator 迭代器和生成器


    1. 迭代器

    1.1 什么是迭代器?

    • 【维基百科】迭代器(iterator),是确使用户可在容器对象(container,例如链表或数组)上遍访的对象,使用该接口无需关心对象的内部实现细节。

      • 其行为像数据库中的光标,迭代器最早出现在 1974 年设计的 CLU 编程语言中;
      • 在各种编程语言的实现中,迭代器的实现方式各不相同,但是基本都有迭代器,比如 Java、Python 等;
    • 从迭代器的定义我们可以看出来,迭代器是帮助我们对某个数据结构进行遍历的对象。

    • 在 JavaScript 中,迭代器也是一个具体的对象,这个对象需要符合迭代器协议(iterator protocol):

      • 迭代器协议定义了产生一系列值(无论是有限还是无限个)的标准方式;
      • 那么在js中这个标准就是一个特定的 next 方法;
    • next 方法有如下的要求:

      • 一个无参数或者一个参数的函数,返回一个应当拥有以下两个属性的对象:
      • done(boolean)
        • 如果迭代器可以产生序列中的下一个值,则为 false。(这等价于没有指定 done 这个属性。)
        • 如果迭代器已将序列迭代完毕,则为 true。这种情况下,value 是可选的,如果它依然存在,即为迭代结束之后的默认返回值。
      • value
        • 迭代器返回的任何 JavaScript 值。donetrue 时可省略。

    1.2 迭代器的代码练习

    // 编写一个迭代器
    /* 
    const iterator = {
      next: function () {
        return { done: true, value: 123 }
      }
    }
     */
    
    // 数组
    const names = ['abc', 'cba', 'nba']
    
    // 创建一个迭代器来访问数组
    let index = 0
    const namesIterator = {
      next: function () {
        /* 
        return { done: false, value: 'abc' }
        return { done: false, value: 'cba' }
        return { done: false, value: 'nba' }
        return { done: true, value: undefined } 
        */
        if (index < names.length) {
          return { done: false, value: names[index++] }
        }
        return { done: true, value: undefined }
      }
    }
    
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    
    /* 
    { done: false, value: 'abc' }
    { done: false, value: 'cba' }
    { done: false, value: 'nba' }
    { done: true, value: undefined }
    { done: true, value: undefined }
    { done: true, value: undefined }
    */
    
    function createArrayIterator(arr) {
      let index = 0
      return {
        next: function () {
          if (index < arr.length) {
            return { done: false, value: arr[index++] }
          }
          return { done: true, value: undefined }
        }
      }
    }
    
    const names = ['abc', 'cba', 'nba']
    const nums = [10, 22, 33, 12]
    
    const namesIterator = createArrayIterator(names)
    const numsIterator = createArrayIterator(nums)
    
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    /* 
    { done: false, value: 'abc' }
    { done: false, value: 'cba' }
    { done: false, value: 'nba' }
    { done: true, value: undefined }
    { done: true, value: undefined }
    { done: true, value: undefined }
    */
    console.log(numsIterator.next())
    console.log(numsIterator.next())
    console.log(numsIterator.next())
    console.log(numsIterator.next())
    console.log(numsIterator.next())
    console.log(numsIterator.next())
    console.log(numsIterator.next())
    /* 
    { done: false, value: 10 }
    { done: false, value: 22 }
    { done: false, value: 33 }
    { done: false, value: 12 }
    { done: true, value: undefined }
    { done: true, value: undefined }
    { done: true, value: undefined }
    */
    
    // 创建一个无限的迭代器
    function createNumberIterator() {
      let index = 0
    
      return {
        next: function () {
          return { done: false, value: index++ }
        }
      }
    }
    

    1.3 可迭代对象

    • 但是 1.2 上面的代码整体来说看起来是有点奇怪的:

      • 我们获取一个数组的时候,需要自己创建一个 index 变量,再创建一个所谓的迭代器对象;
      • 事实上我们可以对上面的代码进行进一步的封装,让其变成一个可迭代对象;
    • 什么又是可迭代对象呢?

      • 它和迭代器是不同的概念;
      • 当一个对象实现了 iterable protocol 协议时,它就是一个可迭代对象;
      • 这个对象的要求是必须实现 @@iterator 方法,在代码中我们使用 Symbol.iterator 访问该属性;
    • 当我们要问一个问题,我们转成这样的一个东西有什么好处呢?

      • 当一个对象变成一个可迭代对象的时候,进行某些迭代操作,比如 for...of 操作时,其实就会调用它的 @@iterator 方法

    1.4 可迭代对象的代码练习

    const iterableObj = {
      names: ['abc', 'cba', 'nba'],
      [Symbol.iterator]: function () {
        let index = 0
        return {
          next: () => {
            if (index < this.names.length) {
              return { done: false, value: this.names[index++] }
            }
            return { done: true, value: undefined }
          }
        }
      }
    }
    
    // iterableObj 是一个可迭代对象
    console.log(iterableObj[Symbol.iterator])
    /* [Function: [Symbol.iterator]] */
    // 1.第一次调用 iterableObj[Symbol.iterator] 函数
    const iterator = iterableObj[Symbol.iterator]()
    console.log(iterator.next())
    console.log(iterator.next())
    console.log(iterator.next())
    console.log(iterator.next())
    console.log(iterator.next())
    /* 
    { done: false, value: 'abc' }
    { done: false, value: 'cba' }
    { done: false, value: 'nba' }
    { done: true, value: undefined }
    { done: true, value: undefined }
    */
    
    // 2.第二次调用 iterableObj[Symbol.iterator] 函数
    const iterator1 = iterableObj[Symbol.iterator]()
    console.log(iterator1.next())
    console.log(iterator1.next())
    console.log(iterator1.next())
    console.log(iterator1.next())
    console.log(iterator1.next())
    /* 
    { done: false, value: 'abc' }
    { done: false, value: 'cba' }
    { done: false, value: 'nba' }
    { done: true, value: undefined }
    { done: true, value: undefined }
    */
    
    // 3. for..of 可以遍历的东西必须是一个可迭代对象
    // 本质上是调用迭代器的 next 方法,当返回值得 done 为 true 的时候,结束循环
    for (const item of iterableObj) {
      console.log(item)
    }
    /* 
    abc
    cba
    nba
    */
    

    1.5 原生迭代器对象

    • 事实上我们平时创建的很多原生对象已经实现了可迭代协议,会生成一个迭代器对象的:
      • StringArrayMapSetarguments 对象、NodeList 集合
    // 1. Array
    const names = ['abc', 'cba', 'nba']
    console.log(names[Symbol.iterator]) // [Function: values]
    const iterator = names[Symbol.iterator]()
    console.log(iterator.next())
    console.log(iterator.next())
    console.log(iterator.next())
    console.log(iterator.next())
    /* 
    { value: 'abc', done: false }
    { value: 'cba', done: false }
    { value: 'nba', done: false }
    { value: undefined, done: true }
    */
    for (const item of names) {
      console.log(item)
    }
    /* 
    abc
    cba
    nba
    */
    
    // 2. Map/Set
    const set = new Set([10, 100, 1000])
    console.log(set[Symbol.iterator]) // [Function: values]
    for (const num of set) {
      console.log(num)
    }
    /* 
    10
    100
    1000
    */
    
    // 3. 函数中的 arguments 也是一个可迭代对象
    function foo(x, y, z) {
      console.log(arguments[Symbol.iterator]) // [Function: values]
      for (const arg of arguments) {
        console.log(arg)
      }
    }
    foo(10, 20, 30)
    /* 
    10
    20
    30
    */
    

    1.6 可迭代对象的应用

    • JavaScript 中语法:for ...of、展开语法(spread syntax)、yield*(后面讲)、解构赋值(Destructuring_assignment);
    • 创建一些对象时:new Map([Iterable])new WeakMap([iterable])new Set([iterable])new WeakSet([iterable]);
    • 一些方法的调用:Promise.all(iterable)Promise.race(iterable)Array.from(iterable)
    // 1. for...of
    
    // 2. 展开运算符
    const iterableObj = {
      names: ['abc', 'cba', 'nba'],
      [Symbol.iterator]: function () {
        let index = 0
        return {
          next: () => {
            if (index < this.names.length) {
              return { done: false, value: this.names[index++] }
            }
            return { done: true, value: undefined }
          }
        }
      }
    }
    
    const names = ['abc', 'cba', 'nba']
    const newNames = [...names, ...iterableObj]
    console.log(newNames)
    /* [ 'abc', 'cba', 'nba', 'abc', 'cba', 'nba' ] */
    
    // 普通对象不能使用 for ... of ,但可以使用展开运算符
    // 是因为普通对象的展开运算符是 ES9(ES2018) 新增的一个特性
    const obj = { name: 'why', age: 18 }
    const newObj = { ...obj } // 此时 obj 不是迭代器对象,是一种新的语法
    
    // 3. 解构语法
    const [name1, name2] = names
    console.log(name1, name2)
    /* abc cba */
    const { nam, age } = obj // 不是迭代器,是一种新的语法
    
    // 4. 创建一些其他对象时
    const set1 = new Set(iterableObj)
    const set2 = new Set([1, 1, 2, 3])
    const arr1 = Array.from(iterableObj)
    console.log(set1, set2, arr1)
    /* Set(3) { 'abc', 'cba', 'nba' } Set(3) { 1, 2, 3 } [ 'abc', 'cba', 'nba' ] */
    
    // 5. Promise.all
    Promise.all(iterableObj).then((res) => {
      console.log(res)
      /* [ 'abc', 'cba', 'nba' ] */
    })
    

    1.7 自定义类的迭代

    • 在前面我们看到 ArraySetStringMap 等类创建出来的对象都是可迭代对象:

      • 在面向对象开发中,我们可以通过 class 定义一个自己的类,这个类可以创建很多的对象
      • 如果我们也希望自己的类创建出来的对象默认是可迭代的,那么在设计类的时候我们就可以添加上 @@iterator 方法
    • 案例:创建一个 classroom 的类

      • 教室中有自己的位置、名称、当前教室的学生
      • 这个教室可以进来新学生(push
      • 创建的教室对象是可迭代对象
      // 案例:创建一个教室类,创建出来的对象是可迭代对象
      class Classroom {
        constructor(address, name, students) {
          this.address = address
          this.name = name
          this.students = students
        }
      
        entry(newStudent) {
          this.students.push(newStudent)
        }
      
        [Symbol.iterator]() {
          let index = 0
          return {
            next: () => {
              if (index < this.students.length) {
                return { done: false, value: this.students[index++] }
              }
              return { done: true, value: undefined }
            }
          }
        }
      }
      
      const classrooom = new Classroom('3幢5楼200', '计算机教室', [
        'james',
        'kobe',
        'curry',
        'why'
      ])
      classrooom.entry('lilei')
      
      for (const stu of classrooom) {
        console.log(stu)
      }
      /* 
      james
      kobe
      curry
      why
      lilei
      */
      

    1.8 迭代器的中断

    • 迭代器在某些情况下会在没有完全迭代的情况下中断:
      • 比如遍历的过程中通过 breakcontinuereturnthrow 中断了循环操作
      • 比如在解构的时候,没有解构所有的值
    • 那么这个时候我们想要监听中断的话,可以添加 return 方法
    // 案例:创建一个教室类,创建出来的对象是可迭代对象
    class Classroom {
      constructor(address, name, students) {
        this.address = address
        this.name = name
        this.students = students
      }
    
      entry(newStudent) {
        this.students.push(newStudent)
      }
    
      [Symbol.iterator]() {
        let index = 0
        return {
          next: () => {
            if (index < this.students.length) {
              return { done: false, value: this.students[index++] }
            }
            return { done: true, value: undefined }
          },
          return: () => {
            console.log('迭代器提前终止了')
            return { done: true, value: undefined }
          }
        }
      }
    }
    
    const classrooom = new Classroom('3幢5楼200', '计算机教室', [
      'james',
      'kobe',
      'curry',
      'why'
    ])
    classrooom.entry('lilei')
    
    for (const stu of classrooom) {
      console.log(stu)
      if (stu === 'why') {
        break
      }
    }
    /* 
    james
    kobe
    curry
    why
    迭代器提前终止了
    */
    

    2. 生成器

    2.1 什么是生成器?

    • 生成器是 ES6 中新增的一种函数控制、使用的方案,它可以让我们更加灵活的控制函数什么时候继续执行、暂停执行等
    • 平时我们会编写很多的函数,这些函数终止的条件通常是返回值或者发生了异常
    • 生成器函数也是一个函数,但是和普通的函数有一些区别:
      • 首先,生成器函数需要在 function 的后面加一个符号:*
      • 其次,生成器函数可以通过 yield 关键字来控制函数的执行流程
      • 最后,生成器函数的返回值是一个 Generator(生成器)
        • 生成器事实上是一种特殊的迭代器;
        • MDN:Instead, they return a special type of iterator, called a Generator.
    function* foo() {
      console.log('函数开始执行~')
      const value1 = 100
      console.log('第一段代码,', value1)
      yield
    
      const value2 = 200
      console.log('第二段代码,', value2)
      yield
    
      const value3 = 300
      console.log('第三段代码,', value3)
      yield
    
      console.log('函数执行结束~')
    }
    
    // 调用生成器函数时,会返回一个生成器对象
    const generator = foo()
    // 开始执行第一段代码
    generator.next()
    // 开始执行第二段代码
    generator.next()
    // 开始执行第三段代码
    generator.next()
    // 结束
    generator.next()
    
    /* 
    函数开始执行~
    第一段代码, 100
    第二段代码, 200
    第三段代码, 300
    函数执行结束~
    */
    

    2.2 生成器函数执行

    • 我们发现上面的生成器函数 foo 的执行体压根没有执行,它只是返回了一个生成器对象。
      • 那么我们如何可以让它执行函数中的东西呢?调用 next即可
      • 我们之前学习迭代器时,知道迭代器的 next 是会有返回值的
      • 但是我们很多时候不希望 next 返回的是一个 undefined,这个时候我们可以通过 yield 来返回结果
    // 当遇到 yeild 时候是暂停函数的执行
    // 当遇到 return 时候是终止函数的执行
    function* foo() {
      console.log('函数开始执行~')
      const value1 = 100
      console.log('第一段代码,', value1)
      yield value1
    
      const value2 = 200
      console.log('第二段代码,', value2)
      yield value2
    
      const value3 = 300
      console.log('第三段代码,', value3)
      yield value3
    
      console.log('函数执行结束~')
      return '123'
    }
    
    // generator 本质上是一个迭代器 iterator
    const generator = foo()
    // 开始执行第一段代码
    console.log('返回值:', generator.next())
    // 开始执行第二段代码
    console.log('返回值:', generator.next())
    // 开始执行第三段代码
    console.log('返回值:', generator.next())
    // 结束
    console.log('返回值:', generator.next())
    /* 
    函数开始执行~
    第一段代码, 100
    返回值: { value: 100, done: false }
    第二段代码, 200
    返回值: { value: 200, done: false }
    第三段代码, 300
    返回值: { value: 300, done: false }
    函数执行结束~
    返回值: { value: '123', done: true }
    */
    

    2.3 生成器传递参数 – next 函数

    • 函数既然可以暂停来分段执行,那么函数应该是可以传递参数的,我们是否可以给每个分段来传递参数呢?
      • 答案是可以的
      • 我们在调用 next 函数的时候,可以给它传递参数,那么这个参数会作为上一个 yield 语句的返回值
      • 注意:也就是说我们是为本次的函数代码块执行提供了一个值
    function* foo(num) {
      console.log('函数开始执行~')
      const value1 = 100 * num
      console.log('第一段代码,', value1)
      const n = yield value1
    
      const value2 = 200 * n
      console.log('第二段代码,', value2)
      const m = yield value2
    
      const value3 = 300 + m
      console.log('第三段代码,', value3)
      yield value3
    
      console.log('函数执行结束~')
      return '123'
    }
    
    // generator 本质上是一个迭代器 iterator
    const generator = foo(5)
    // 开始执行第一段代码
    console.log('返回值:', generator.next())
    // 开始执行第二段代码 第二次调用next时候执行
    console.log('返回值:', generator.next(10))
    // 开始执行第三段代码
    console.log('返回值:', generator.next(25))
    // 结束
    console.log('返回值:', generator.next())
    /* 
    函数开始执行~
    第一段代码, 500
    返回值: { value: 500, done: false }
    第二段代码, 2000
    返回值: { value: 2000, done: false }
    第三段代码, 325
    返回值: { value: 325, done: false }
    函数执行结束~
    返回值: { value: '123', done: true }
    */
    

    2.4 生成器提前结束 – return 函数

    • 还有一个可以给生成器函数传递参数的方法是通过 return 函数:
      • return 传值后这个生成器函数就会结束,之后调用 next 不会继续生成值了
    function* foo(num) {
      console.log('函数开始执行~')
      const value1 = 100 * num
      console.log('第一段代码,', value1)
      const n = yield value1
      // return n
    
      const value2 = 200 * n
      console.log('第二段代码,', value2)
      const m = yield value2
    
      const value3 = 300 + m
      console.log('第三段代码,', value3)
      yield value3
    
      console.log('函数执行结束~')
      return '123'
    }
    
    // generator 本质上是一个迭代器 iterator
    const generator = foo(5)
    // 开始执行第一段代码
    console.log('返回值:', generator.next())
    // 第二段代码的执行,使用了 return
    // 那么就意味着相当于在第一段的后面加上 return,就会提前终止生成器代码的执行
    console.log('返回值:', generator.return(15))
    console.log('返回值:', generator.next())
    
    /* 
    函数开始执行~
    第一段代码, 500
    返回值: { value: 500, done: false }
    返回值: { value: 15, done: true }
    返回值: { value: undefined, done: true }
    */
    

    2.5 生成器抛出异常 – throw 函数

    • 除了给生成器函数内部传递参数之外,也可以给生成器函数内部抛出异常:
      • 抛出异常后我们可以在生成器函数中捕获异常
    function* foo() {
      console.log('代码开始执行~')
    
      const value1 = 100
      try {
        yield value1
      } catch (error) {
        console.log('捕获到异常情况, ', error)
      }
    
      console.log('第二段代码继续执行')
      const value2 = 200
      yield value2
    
      console.log('代码执行结束~')
    }
    
    const generator = foo()
    
    console.log(generator.next())
    console.log(generator.throw('error message'))
    console.log(generator.next())
    
    /* 
    代码开始执行~
    { value: 100, done: false }
    捕获到异常情况,  error message
    第二段代码继续执行
    { value: 200, done: false }
    代码执行结束~
    { value: undefined, done: true }
    */
    
    function* foo() {
      console.log('代码开始执行~')
    
      const value1 = 100
      try {
        yield value1
      } catch (error) {
        console.log('捕获到异常情况, ', error)
      }
    
      console.log('第二段代码继续执行')
      const value2 = 200
      yield value2
    
      console.log('代码执行结束~')
    }
    
    const generator = foo()
    
    const result = generator.next()
    // 返回值不符合预期,抛出异常
    if (result !== 200) {
      console.log(generator.throw('error message'))
    }
    
    /* 
    代码开始执行~
    捕获到异常情况,  error message
    第二段代码继续执行
    { value: 200, done: false }
    */
    
    

    2.6 生成器替代迭代器

    • 我们发现生成器是一种特殊的迭代器,那么在某些情况下我们可以使用生成器来替代迭代器
    // 迭代器
    // function createArrayIterator(arr) {
    //   let index = 0
    //   return {
    //     next() {
    //       if (index < arr.length) {
    //         return { done: false, value: arr[index++] }
    //       }
    //       return { done: true, value: undefined }
    //     }
    //   }
    // }
    
    // 生成器替代迭代器
     function* createArrayIterator1(arr) {
       let index = 0
       yield arr[index++]
       yield arr[index++]
       yield arr[index++]
    }
    function* createArrayIterator2(arr) {
      for (const item of arr) {
        yield item
      }
    }
    
    const names = ['abc', 'cba', 'nba']
    // const namesIterator = createArrayIterator1(names)
    const namesIterator = createArrayIterator2(names)
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    
    /* 
    { value: 'abc', done: false }
    { value: 'cba', done: false }
    { value: 'nba', done: false }
    { value: undefined, done: true }
    */
    
    • 事实上我们还可以使用 yield* 来生产一个可迭代对象:
      • 这个时候相当于是第2种 yield 的语法糖,只不过会依次迭代这个可迭代对象,每次迭代其中的一个值
    function* createArrayIterator(arr) {
      yield* arr
    }
    
    const names = ['abc', 'cba', 'nba']
    const namesIterator = createArrayIterator(names)
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    /* 
    { value: 'abc', done: false }
    { value: 'cba', done: false }
    { value: 'nba', done: false }
    { value: undefined, done: true }
    */
    
    // 2. 创建一个函数,这个函数可以迭代一个范围内的数字
    // function createRangeIterator(start, end) {
    //   let index = start
    //   return {
    //     next() {
    //       if (index <= end) {
    //         return { done: false, value: index++ }
    //       }
    //       return { done: false, value: undefined }
    //     }
    //   }
    // }
    
    function* createRangeIterator(start, end) {
      let index = start
      while (index < end) {
        yield index++
      }
    }
    
    const rangeIterator = createRangeIterator(10, 20)
    console.log(rangeIterator.next())
    console.log(rangeIterator.next())
    console.log(rangeIterator.next())
    console.log(rangeIterator.next())
    /*
    { value: 10, done: false }
    { value: 11, done: false }
    { value: 12, done: false }
    { value: 13, done: false }
    */
    
    • 在之前的自定义类迭代中,我们也可以换成生成器:
    // 3. class 案例
    // 案例:创建一个教室类,创建出来的对象是可迭代对象
    class Classroom {
      constructor(address, name, students) {
        this.address = address
        this.name = name
        this.students = students
      }
    
      entry(newStudent) {
        this.students.push(newStudent)
      }
    
      *[Symbol.iterator]() {
        yield* this.students
      }
    }
    
    const classrooom = new Classroom('3幢5楼200', '计算机教室', [
      'james',
      'kobe',
      'curry',
      'why'
    ])
    classrooom.entry('lilei')
    
    for (const stu of classrooom) {
      console.log(stu)
      if (stu === 'why') {
        break
      }
    }
    /* 
    james
    kobe
    curry
    why
    迭代器提前终止了
    */
    

    2.7 对生成器的操作

    • 既然生成器是一个迭代器,那么我们可以对其进行如下的操作
    const namesIterator1 = createArrayIterator(names)
    for (const item of namesIterator1) {
      console.log(item)
    }
    
    const namesIterator2 = createArrayIterator(names)
    const set = new Set(namesIterator2)
    console.log(set)
    
    const namesIterator3 = createArrayIterator(names)
    Promise.all(namesIterator3).then((res) => {
      console.log(res)
    })
    

    2.8 异步处理方案

    • 学完了我们前面的 Promise、生成器等,我们目前来看一下异步代码的最终处理方案。

    • 需求:

      • 我们需要向服务器发送网络请求获取数据,一共需要发送三次请求
      • 第二次的请求 url 依赖于第一次的结果;
      • 第三次的请求url依赖于第二次的结果;
      • 依次类推;
    function requestData(url) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(url)
        }, 200)
      })
    }
    
    // 需求:
    // 1> url: why -> res: why
    // 2> url: res + 'aaa' -> res: whyaaa
    // 3> url: res + 'bbb' -> res: whyaaabbb
    
    // 1. 第一种方案
    // 回调地狱
    requestData('coderwhy').then((res) => {
      requestData(res + 'aaa').then((res) => {
        requestData(res + 'bbb').then((res) => {
          console.log(res)
        })
      })
    })
    
    // 2. 第二种方案: Promise 的返回值来解决
    requestData('coderwhy')
      .then((res) => {
        return requestData(res + 'aaa')
      })
      .then((res) => {
        return requestData(res + 'bbb')
      })
      .then((res) => {
        console.log(res)
      })
    
    // 3. 第三种方案: Promise + generator 实现
    function* genData() {
      const res1 = yield requestData('why')
      const res2 = yield requestData(res1 + 'aaa')
      const res3 = yield requestData(res2 + 'bbb')
      console.log(res3)
    }
    
    const generator = genData()
    generator.next().value.then((res) => {
      generator.next(res).value.then((res) => {
        generator.next(res).value.then((res) => {
          generator.next(res)
        })
      })
    })
    

    2.9 Genetator 方案

    • 是上面的代码其实看起来也是阅读性比较差的,有没有办法可以继续来对上面的代码进行优化呢?

    • 自动执行 generator 函数

      • 目前我们的写法有两个问题:

        • 第一,我们不能确定到底需要调用几层的 Promise 关系;

        • 第二,如果还有其他需要这样执行的函数,我们应该如何操作呢?

      • 所以,我们可以封装一个工具函数 execGenerator 自动执行生成器函数

    function* genData() {
      const res1 = yield requestData('why')
      const res2 = yield requestData(res1 + 'aaa')
      const res3 = yield requestData(res2 + 'bbb')
      console.log(res3)
    }
    
    // 1> 手动执行生成器函数
    /* 
    const generator = genData()
    generator.next().value.then((res) => {
      generator.next(res).value.then((res) => {
        generator.next(res).value.then((res) => {
          generator.next(res)
        })
      })
    }) 
    */
    
    // 2> 自己封装了一个自动执行的函数
    function execGenerator(genFn) {
      const generator = genFn()
    
      function exec(res) {
        const result = generator.next(res)
        if (result.done) {
          return result.value
        }
    
        result.value.then((res) => {
          exec(res)
        })
      }
    
      exec()
    }
    
    execGenerator(genData)
    
    // 3> 第三方包 co 自动执行
    const co = require('co')
    co(genData)
    
    // 4> 第4种方案:async/await
    async function genData2() {
      const res1 = await requestData('why')
      const res2 = await requestData(res1 + 'aaa')
      const res3 = await requestData(res2 + 'bbb')
      console.log(res3)
    }
    
    genData2()
    

    3. await-async

    3.1 异步函数 async function

    • async 关键字用于声明一个异步函数:

      • asyncasynchronous 单词的缩写,异步、非同步;
      • syncsynchronous 单词的缩写,同步、同时;
    • async 异步函数可以有很多中写法:

      async function foo1() {}
      
      const foo2 = async () => {}
      
      class Foo {
        async bar() {}
      }
      

    3.2 异步函数的执行流程

    • 异步函数的内部代码执行过程和普通的函数是一致的,默认情况下也是会被同步执行

    • 异步函数有返回值时,和普通函数会有区别:

      • 情况一:异步函数也可以有返回值,但是异步函数的返回值会被包裹到 Promise.resolve
      • 情况二:如果我们的异步函数的返回值是 PromisePromise.resolve 的状态会由 Promise 决定
      • 情况三:如果我们的异步函数的返回值是一个对象并且实现了 thenable,那么会由对象的 then 方法来决定
      async function foo() {
        console.log('foo function start~')
        console.log('中间代码~')
        console.log('foo function end~')
      
        // 1. 返回一个值
        /* return 123 */
      
        // 2. 返回 thenable
        /* return {
          then: function (resolve, reject) {
            resolve('hahahah')
          }
        } */
      
        // 3. 返回一个 Promise
        return new Promise((resolve, reject) => {
          resolve('heheheh')
          setTimeout(() => {}, 2000)
        })
      }
      
      // 异步函数的返回值一定是一个 Promise
      const promise = foo()
      
      promise.then((res) => {
        console.log('promise then function exex:', res)
      })
      
    • 如果我们在 async 中抛出了异常,那么程序它并不会像普通函数一样报错,而是会作为 Promisereject 来传递

      async function foo() {
        console.log('foo function start~')
      
        console.log('中间代码~')
      
        // 异步函数中的异常,会被作为异步函数返回的 Promise 的 reject 值的
        throw new Error('error message')
        console.log('foo function end~')
      }
      
      // 异步函数的返回值一定是一个 Promise
      const promise = foo()
      
      promise.catch((err) => {
        console.log('error: ', err)
      })
      
      console.log('后续还有代码')
      

    3.3 await 关键字

    • async 函数另外一个特殊之处就是可以在它内部使用 await 关键字,而普通函数中是不可以的
    • await 关键字有什么特点呢?
      • 通常使用 await 是后面会跟上一个表达式,这个表达式会返回一个 Promise
      • 那么 await 会等到 Promise 的状态变成 fulfilled 状态,之后继续执行异步函数
    • 如果 await 后面是一个普通的值,那么会直接返回这个值
    • 如果 await 后面是一个 thenable 的对象,那么会根据对象的 then 方法调用来决定后续的值
    • 如果 await 后面的表达式,返回的 Promisereject 的状态,那么会将这个 reject 结果直接作为函数的 Promise

    reject

    // 1.await更上表达式
    function requestData() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          // resolve(222)
          reject(1111)
        }, 2000);
      })
    }
    
    // async function foo() {
    //   const res1 = await requestData()
    //   console.log("后面的代码1", res1)
    //   console.log("后面的代码2")
    //   console.log("后面的代码3")
    
    //   const res2 = await requestData()
    //   console.log("res2后面的代码", res2)
    // }
    
    // 2.跟上其他的值
    // async function foo() {
    //   // const res1 = await 123
    //   // const res1 = await {
    //   //   then: function(resolve, reject) {
    //   //     resolve("abc")
    //   //   }
    //   // }
    //   const res1 = await new Promise((resolve) => {
    //     resolve("why")
    //   })
    //   console.log("res1:", res1)
    // }
    
    // 3.reject值
    async function foo() {
      const res1 = await requestData()
      console.log("res1:", res1)
    }
    
    foo().catch(err => {
      console.log("err:", err)
    })
    
  • 相关阅读:
    从零学习Linux操作系统 第三十二部分 ansible中剧本的应用
    前端学习 linux —— 第一篇
    Fiber 架构实现流程
    【ML】 第四章 训练模型
    Swagger系列:SpringBoot3.x中使用Knife4j
    影响WebPack部署的常见因素及解决办法
    SpringSecurity系列——基于SpringBoot2.7的登录接口(内有惊喜)day2-1
    Pandas Excel数据处理指南
    Reactive UI -- 反应式编程UI框架入门学习(一)
    K8s部署轻量级日志收集系统EFK(elasticsearch + filebeat + kibana)
  • 原文地址:https://blog.csdn.net/wanghuan1020/article/details/127098639