使用Generator函数做遍历器

使用Generator函数做遍历器


Generator 函数是 ES6 提供的一种异步编程解决方案,使用Generator 函数能够方便的解决很多异步遍历问题。

定义:

// 1 定义
function* howToLaugh() {
  yield '嘿嘿';
  yield '嘻嘻';
  return '哈哈哈';
};
// 2 调用
// 调用但并不执行,返回的也不是函数运行结果,而是一个指向内部状态的指针对象
let laugh = howToLaugh(); 
// 3 next()
// 必须调用next方法,代码才会往下执行直到遇到yield表达式(或return语句)。
// 即yield表达式是暂停执行的标记,而next方法可以恢复执行
// 另 next方法会返回一个对象,对象的value属性就是当前yield表达式的值,done属性的值表示函数是否运行结束。
laugh.next() // => 函数进行到yield '嘿嘿'停止
// {value: "嘿嘿", done: false}

在vue中做遍历器:

data() {
  return {
  	letsLaughGenerator: null,
    laughtTime: 3,
  }
},
methods: {
  async firstLaugh () {
    this.letsLaughGenerator = await this.letsLaugh()
    this.letsLaughGenerator.next()
  },
  * letsLaugh() {
    for (var i = this.laughtTime; i > 0; i--) {
      console.log('i', i)
      this.justLaugh()
      yield i
    }
    return 'end'
  },
  justLaugh () {
    setTimeout(() => {
      // todo
      console.log('continue!')
      this.letsLaughGenerator.next()
    }, 2000)
  },
},
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值