[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>
相关推荐
phltxy13 分钟前
从零入门JavaScript:基础语法全解析
开发语言·javascript
烛阴14 分钟前
从“无”到“有”:手动实现一个 3D 渲染循环全过程
前端·webgl·three.js
BD_Marathon26 分钟前
SpringBoot——辅助功能之切换web服务器
服务器·前端·spring boot
Kagol26 分钟前
JavaScript 中的 sort 排序问题
前端·javascript
eason_fan1 小时前
Service Worker 缓存请求:前端性能优化的进阶利器
前端·性能优化
光影少年1 小时前
rn如何和原生进行通信,是单线程还是多线程,通信方式都有哪些
前端·react native·react.js·taro
好大哥呀1 小时前
Java Web的学习路径
java·前端·学习
HashTang1 小时前
【AI 编程实战】第 7 篇:登录流程设计 - 多场景、多步骤的优雅实现
前端·uni-app·ai编程
cos2 小时前
Fork 主题如何更新?基于 Ink 构建主题更新 CLI 工具
前端·javascript·git
小满zs2 小时前
Next.js第二十一章(环境变量)
前端·next.js