Generator
Generator函数是ES6提供的一种异步编程解决方案
.
Generator 对象由生成器函数返回并且它符合可迭代协议和迭代器协议。
Generator 是隐藏类 Iterator 的子类。
.
.
.
尝试一下:
const mall = function* () {
yield 'apple'
yield 'banana'
yield 'cherry'
}
let food = ''
for (let i of mall()) {
food += i + ' '
}
console.log(food)

.
.
.
使用next()
const mall = function* () {
yield 'apple'
yield 'banana'
yield 'cherry'
}
// let food = ''
// for (let i of mall()) {
// food += i + ' '
// }
// console.log(food)
const food = mall()

此处的done表示generator函数中有没有走完yield
.
.
..
使用forof
const mall = function* () {
yield 'apple'
yield 'banana'
yield 'cherry'
}
// let food = ''
// for (let i of mall()) {
// food += i + ' '
// }
// console.log(food)
const food = mall()
for (const iterator of food) {
console.log(iterator);
}

.
.
.
异步调用
<script>
const findCity = function* () {
yield axios('URL?p')
yield axios('URL?p')
}
const logCity = findCity()
logCity.next().value.then(res => {
console.log(res.data.list)
return logCity.next().value
}).then(res => {
console.log(res.data.list)
})
</script>
浙公网安备 33010602011771号