function* gen() {
yield '1';
yield '2';
yield '3';
}
const a = gen(); // 这一步不能省略,很重要,如果a消费完了,你要重新获取就const b = gen() 继续next()
console.log(a.next());
console.log(a.next());
console.log(a.next());
console.log(a.next());
// 遍历
for (const b of gen()) {
console.log(b);
}
模拟异步变同步
function* gen() {
const d1 = yield data1();
const d2 = yield data2();
console.log(d1);
console.log(d2);
}
const generator = gen();
const data1 = () => {
setTimeout(() => {
generator.next('11111');
}, 2000);
};
const data2 = () => {
setTimeout(() => {
generator.next('2222');
}, 1000);
};
generator.next();