What is a generator
- Is a special function, a special iterator (Iterator)
- Definition: There is an asterisk before the function name, and the yield syntax is used internally.
- Returns: an iterator containing the next method inside
- Execution: Consume the generator by calling the next() method until the yield keyword is encountered.
function * gen(){
console.log('hello generator!')
}
let genResult = gen()
console.log('genResult=',genResult)
demo: iteration of the generator
function * gen(){
yield "小学生";
yield "中学生"
yield "大学生"
}
for (const v of gen()) {
console.log('v=',v)
}
demo: generator executes next
- The parameter of yield is the return value of next method
- yield divides the code into N sections for execution
- The next method can be executed in sections
function * gen(){
console.log('111')
yield "小学生";
console.log('222')
yield "中学生"
console.log('333')
yield "大学生"
console.log('444')
}
let g = gen()
console.log('g.next()=',g.next())
console.log('g.next()=',g.next())
console.log('g.next()=',g.next())
console.log('g.next()=',g.next())
demo: return value of generator yield
- The parameter of next method is the return value of yield
- The parameter of the Nth next method is the return value of N-1 yield
function * gen(){
const one = yield "小学生"
console.log('one=',one)
const two = yield "中学生"
console.log('two=',two)
const three = yield "大学生"
console.log('three=',three)
}
const g = gen()
g.next();
g.next('AAA');
g.next('BBB');
g.next('CCC');
demo: Synchronized expression of asynchronous tasks
- Requirements: Get the results of asynchronous requests in order
- Sequence: User data-》Order data-》Product data
- Asynchronous: Use settimout simulation
function getData() {
let result = []
setTimeout(() => {
result.push('用户数据')
setTimeout(() => {
result.push('订单数据')
setTimeout(() => {
result.push('商品数据')
consumeData(result)
}, 500)
}, 500);
}, 500)
}
function consumeData(data) {
console.log('data=', data)
}
getData()
let result = []
function getUsers() {
setTimeout(() => {
console.log('getUsers...')
result.push('用户数据')
iter.next()
}, 500)
}
function getOrders() {
setTimeout(() => {
console.log('getOrders...')
result.push('订单数据')
iter.next()
}, 500)
}
function getGoods() {
setTimeout(() => {
console.log('getGoods...')
result.push('商品数据')
iter.next()
consumeData(result)
}, 500)
}
function* getData() {
console.log('getData start')
yield getUsers()
yield getOrders()
yield getGoods()
console.log('getData end')
}
function consumeData(data) {
console.log('consumeData data=', data)
}
let iter = getData()
iter.next()
demo: combining generators and iterators
const cards = {
suits: ["♣️", "♦️", "♥️", "♠️"],
courts: ["J", "Q", "K", "A"],
[Symbol.iterator]:function*(){
for(let s of this.suits){
for (let i = 2; i < 10; i++) yield s+i
for(let c of this.courts) yield s+c
}
}
}
let result = []
for (const v of cards) {
result.push(v)
}
console.log('result=',result)
console.log('cards=',[...cards])