首页 > 文章列表 > throw在js生成器中的用法

throw在js生成器中的用法

throw js生成器
183 2022-08-06

说明

1、生成器函数的外部可以向throw方法传达参数,该参数被catch语句捕获。

2、不传达参数,catch语句捕获为undefined,catch语句捕获后恢复生成器的执行,具有IteratorResult。

实例

const caughtInsideCounter = (function* () {
  let c = 0;
  while (true) {
    try {
      yield ++c;
    } catch (e) {
      console.log(e);
    }
  }
})();
 
caughtInsideCounter.next();    // { value: 1, done: false}
caughtIndedeCounter.throw(new Error('An error occurred!'));
// 输出 An error occurred!
// { value: 2, done: false }

推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。