AsyncGenerator.prototype.next()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
AsyncGenerator
实例的 next()
方法返回序列中的下一个值。
语法
js
next()
next(value)
参数
value
可选-
用于修改生成器内部状态的可选值。传入给
next()
方法的值将被yield
接收。
返回值
示例
使用 next()
以下示例展示了一个简单的生成器以及调用 next
方法后返回的对象:
js
// 异步任务。假设它在实践中做了一些更有用的事情。
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 }
向生成器传值
在此示例中,调用 next
时传入了值。
备注: 第一次调用不会打印任何内容,因为生成器最初没有产生任何内容。
js
// 异步任务。假设它在实践中做了一些更有用的事情。
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();
// 这一步不会有输出:通过 `next` 发送的第一个值会被丢弃
console.log(await asyncGen.next(1)); // { value: undefined, done: false }
// 打印通过 `next` 发送的值——2
console.log(await asyncGen.next(2)); // { value: undefined, done: false }
}
main();
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-asyncgenerator-prototype-next |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
next |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.