javascript - forEach循环yield 出错

查看:102
本文介绍了javascript - forEach循环yield 出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

lamb是一组函数.

const sign = ['red', 'green', 'yellow'];

function tic(str, timer) {
  return () => new Promise((res, rej) => {
    setTimeout(() => {
      console.log(str);
      res();
    }, timer);
  });
}

const lamb = sign.reduce(function (prev, item) {
  prev.push(tic(item, 1000));

  return prev;
}, []);

const gen = function* () {
  lamb.forEach(function (item, index) {
    yield item();
  });

  // for(let i = 0; i < lamb.length; i++) {
  //   yield lamb[i]();
  // }

  //for(let i in lamb) {
    //yield lamb[i]();
//  }
}

为什么 forEach不行(报错Unexpected identifier),for(let i = 0; i < lamb.length; i++) /for(let i in lamb)可以?

解决方案

注意,forEach里面你是传了一个函数进去,所以你的yield语句实际上在一个不是生成器的函数里面,所以当然报错。

这篇关于javascript - forEach循环yield 出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆