使用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)
},
},