[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>
相关推荐
li35744 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj4 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel4 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel4 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
^Rocky5 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
西陵6 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld6 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
笑鸿的学习笔记6 小时前
JavaScript笔记之JS 和 HTML5 的关系
javascript·笔记·html5
东风西巷8 小时前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求