AsyncGenerator.prototype.next()

AsyncGenerator 实例的 next() 方法返回序列中的下一个值。

¥The next() method of AsyncGenerator instances returns the next value in the sequence.

语法

¥Syntax

js
next()
next(value)

参数

¥Parameters

value Optional

用于修改生成器内部状态的可选值。传递给 next() 方法的值将由 yield 接收

返回值

¥Return value

解析后的 Promise 返回具有两个属性的 Object

¥A Promise which when resolved returns an Object with two properties:

done

布尔值:

  • true 如果生成器已超过其控制流的末尾。在这种情况下,value 指定生成器的返回值(可能是未定义的)。
  • 如果生成器能够产生更多值,则为 false
value

由生成器生成或返回的任何 JavaScript 值。

示例

¥Examples

使用 next()

¥Using next()

以下示例显示了一个简单的生成器和 next 方法返回的对象:

¥The following example shows a simple generator and the object that the next method returns:

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

async function* createAsyncGenerator() {
  yield delayedValue(500, 1);
  yield delayedValue(500, 2);
  yield delayedValue(500, 3);
}

const asyncGen = createAsyncGenerator();
asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 2, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 3, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: undefined, done: true }

将值发送到生成器

¥Sending values to the generator

在此示例中,使用值调用 next

¥In this example, next is called with a value.

注意:第一次调用不会记录任何内容,因为生成器最初没有产生任何内容。

¥Note: The first call does not log anything, because the generator was not yielding anything initially.

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) {
    await sleep(500);
    const value = yield;
    console.log(value);
  }
}

async function main() {
  const asyncGen = createAsyncGenerator();
  // No log at this step: the first value sent through `next` is lost
  console.log(await asyncGen.next(1)); // { value: undefined, done: false }
  // Logs 2: the value sent through `next`
  console.log(await asyncGen.next(2)); // { value: undefined, done: false }
}

main();

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看