[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>
相关推荐
KevinCyao7 小时前
Ruby短信营销接口示例代码:Ruby开发环境下营销短信API接口的集成与Demo演示
开发语言·前端·ruby
葳_人生_蕤7 小时前
hot100——双指针法专题
java·前端·数据库
Omics Pro7 小时前
基因集(模块)活性量化:R语言+Java原生
大数据·开发语言·前端·javascript·数据库·r语言·aigc
晓13137 小时前
React篇——第六章 React进阶特性与状态管理
前端·react.js·性能优化
菜鸟茜7 小时前
ES6核心知识解析03:为什么用let和const取代var
前端·javascript·es6
苏瞳儿7 小时前
后端环境配置
javascript
wuhen_n7 小时前
复杂任务拆解:让AI像项目经理一样思考
前端·javascript·ai编程
Arya_aa7 小时前
拿取gitee中现成的vue-manage-system模板
前端·javascript·vue.js
白嫖叫上我7 小时前
弹窗之封装拖拽与拖动拉伸
前端