AsyncGenerator.prototype.throw()

AsyncGenerator 实例的 throw() 方法的作用就好像在生成器主体的当前挂起位置插入了一条 throw 语句,该语句向生成器通知错误情况并允许其处理错误,或者执行清理并自行关闭。

¥The throw() method of AsyncGenerator instances acts as if a throw statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.

语法

¥Syntax

js
asyncGeneratorInstance.throw(exception)

参数

¥Parameters

exception

要抛出的异常。出于调试目的,将其设置为 instanceof Error 很有用。

返回值

¥Return value

如果抛出的错误没有被捕获,它将返回一个 Promise,它会拒绝传入的异常。

¥If the thrown error is not caught, it will return a Promise which rejects with the exception passed in.

如果异常被 try...catch 捕获并且生成器恢复生成更多值,它将返回 Promise,该 Promise 解析为具有两个属性的 Object

¥If the exception is caught by a try...catch and the generator resumes to yield more values, it will return a Promise which resolves with an Object with two properties:

done

布尔值:

  • 如果生成器函数的控制流已到达末尾,则为 true
  • false 如果生成器函数能够产生更多值。
value

从下一个 yield 表达式产生的值。

示例

¥Examples

使用 throw()

¥Using throw()

以下示例显示了一个简单的生成器以及使用 throw 方法引发的错误。像往常一样,错误可以被 try...catch 块捕获。

¥The following example shows a simple generator and an error that is thrown using the throw method. An error can be caught by a try...catch block as usual.

js
// An async task. Pretend it's doing something more useful
// in practice.
function sleep(time) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, time);
  });
}

async function* createAsyncGenerator() {
  while (true) {
    try {
      await sleep(500);
      yield 42;
    } catch (e) {
      console.error(e);
    }
  }
}

const asyncGen = createAsyncGenerator();
asyncGen.next(1).then((res) => console.log(res)); // { value: 42, done: false }
asyncGen
  .throw(new Error("Something went wrong")) // Error: Something went wrong
  .then((res) => console.log(res)); // { value: 42, done: false }

规范

Specification
ECMAScript Language Specification
# sec-asyncgenerator-prototype-throw

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看