[JS]Generator

介绍

Generator函数是 ES6 提供的一种异步编程解决方案, async是该方案的语法糖

核心语法

Generator对象由生成器函数返回, 并且它符合可迭代协议和迭代器协议

生成器函数在执行时能暂停, 后面又从暂停处继续执行

复制代码
<script>
    // 1.定义生成器函数
    function* testGenerator() {
      console.log('生成器对象执行了');
      yield '异步任务1'
      yield '异步任务2'
      yield '异步任务3'
    }

    // 2.获取Generator对象
    const test = testGenerator()

    // 3.next()方法
    // 手动执行
    console.log(test.next()); // 生成器对象执行了 / {value: '异步任务1', done: false}
    console.log(test.next()); // {value: '异步任务2', done: false}
    console.log(test.next()); // {value: '异步任务3', done: false}
    console.log(test.next()); // {value: 'undefiend', done: true}

    // 4.for of循环
    // 循环执行
    for (const item of testGenerator()) {
      console.log(item);
    }
  </script>

管理异步

使用Generator对象管理异步任务, 在定义的时候比较直观, 但是调用还是比较繁琐, 所以才会出现async语法糖

复制代码
<script>
    // 1.创建一个生成器
    function* cityGenerator() {
      yield fetch('http://hmajax.itheima.net/api/city?pname=北京');
      yield fetch('http://hmajax.itheima.net/api/city?pname=天津');
    }

    // 2.获取生成器对象
    const city = cityGenerator();

    // 3.通过netx方法执行代码
    city.next().value.then((res)=>{
      // 4.拿到第一个任务的成功结果
      console.log('res', res.json());
      // 5.执行下一个异步任务
      return city.next().value
    }).then((res)=>{
      // 6.拿到第一个任务的成功结果
      console.log('res', res.json());
    })
  </script>
相关推荐
mCell1 天前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip1 天前
Node.js 子进程:child_process
前端·javascript
excel1 天前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel1 天前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼1 天前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript