为什么在循环中从未调用`throw`迭代器接口方法?

问题描述

根据ECMAScript规范,实现Iterator Interface的对象必须具有next方法,但是还有可选的returnthrow方法(请参见此处的规范:{{3} })

代码段中提供了示例代码,为什么在循环循环中从未调用throw方法,却又调用return方法

class Iterable {
  constructor(name) {
    this.name = name;
  }
  [Symbol.iterator]() {
    let done = false;

    function implementation() {
      if (done) {
        return {
          done: true,value: undefined,};
      }
      done = true;
      return {
        done: false,};
    }

    return {
      next: (...args) => {
        console.log(
          `${this.name}: next called,done=${JSON.stringify(
            done
          )},args=${JSON.stringify(args)}`
        );
        return implementation();
      },return: (...args) => {
        console.log(
          `${this.name}: return called,throw: (...args) => {
        console.log(
          `${this.name}: throw called,};
  }
}

(() => {
  for (const item of new Iterable("standard")) {
    // pass
  }
})();

(() => {
  for (const item of new Iterable("return")) {
    return "test";
  }
})();

(() => {
  for (const item of new Iterable("break")) {
    break;
  }
})();

(() => {
  for (const item of new Iterable("continue")) {
    continue;
  }
})();

(() => {
  try {
    for (const item of new Iterable("throw")) {
      throw new Error(`${item}`);
    }
  } catch {
    // pass
  }
})();

控制台输出

standard: next called,done=false,args=[]
standard: next called,done=true,args=[]
return: next called,args=[]
return: return called,args=[]
break: next called,args=[]
break: return called,args=[]
continue: next called,args=[]
throw: next called,args=[]
throw: return called,args=[]

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)