[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>
  • 14
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值