美文网首页
gennerator 函数

gennerator 函数

作者: 候鸟_ywh | 来源:发表于2020-04-06 14:40 被阅读0次
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();

相关文章

网友评论

      本文标题:gennerator 函数

      本文链接:https://www.haomeiwen.com/subject/ducbphtx.html