Async generators
非同期ジェネレータは async function* で宣言し、await で非同期データを取得しながら yield で値を逐次返します。for await...of で反復します。
概要
非同期ジェネレータは async function* で宣言し、await で非同期データを取得しながら yield で値を逐次返します。for await...of で反復します。
対応ブラウザ
| 機能 | デスクトップ | モバイル | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 63 | 79 | 55 | 12 | 63 | 12 | |
| next() メソッドは、シーケンス内の次の値を返します。 | 63 | 79 | 55 | 12 | 63 | 12 |
| return() は AsyncGenerator インスタンスのメソッドで、あたかも return 文がジェネレーター本体の中の停止中の位置に挿入されたかのように動作し、ジェネレーターを終了して、try...finally ブロックと組み合わせた際に、ジェネレーターが任意のクリーンアップタスクを実行できるようにします。 | 63 | 79 | 55 | 12 | 63 | 12 |
| throw() は AsyncGenerator インスタンスのメソッドで、あたかも throw 文がジェネレーター本体の中の停止中の位置に挿入されたかのように動作し、エラー状態をジェネレーターに通知して、エラーを処理するか、クリーンアップを実行してそれ自身を閉じることができます。 | 63 | 79 | 55 | 12 | 63 | 12 |
| その他 | ||||||
| AsyncGeneratorFunction オブジェクトは、非同期ジェネレーター関数のメソッドを提供します。 JavaScript では、すべての非同期ジェネレータ関数は実際には AsyncGeneratorFunction オブジェクトです。 | 63 | 79 | 55 | 12 | 63 | 12 |
| ビルトインオブジェクト | ||||||
| AsyncGeneratorFunction() コンストラクターは AsyncGeneratorFunction オブジェクトを生成します。 | 63 | 79 | 55 | 12 | 63 | 12 |
| その他 | ||||||
javascript.functions.method_definitions.async_generator_methods 非同期ジェネレーター・メソッド | 63 | 79 | 57 | 12 | 63 | 12 |
| 非同期関数*`式 | 63 | 79 | 57 | 12 | 63 | 12 |
| 非同期関数*`ステートメント | 63 | 79 | 57 | 12 | 63 | 12 |
基本構文
async function* fetchPages(url) {
let page = 1;
while (true) {
const res = await fetch(`${url}?page=${page}`);
const data = await res.json();
if (data.length === 0) return;
yield data;
page++;
}
}
for await (const page of fetchPages('/api/items')) {
console.log(page);
} ライブデモ
async function* Basics
asyncgenerator definition.await and yield combinationpossible. with async function*
Normal generator and. Difference
different. with Yield value that sync/async, side that for...of / for await...of.
実務での使いどころ
-
Async generators の活用
非同期イテレータを生成する関数。async function* で宣言し、await と yield を組み合わせ可能。
注意点
- 特になし。すべての主要ブラウザで安定して動作する。
アクセシビリティ
- JavaScript による動的更新時は、aria-live リージョンで変更をスクリーンリーダーに通知する。
参考リンク
Powered by web-features