JavaScript Array.fromAsync() メソッド
例
非同期反復可能オブジェクトから配列を作成:
試してみる »
定義と用法
Array.fromAsync() は、JavaScript の比較的新しい静的メソッドで、非同期反復可能オブジェクト、反復可能オブジェクト、または配列ライクオブジェクトから新しい配列を作成できます。このメソッドは、新しい配列インスタンスに解決される Promise を返します。
簡単に言うと、Array.from() の非同期版であり、非同期データソースを処理するために特化しています。
基本構文
Array.fromAsync(iterable)
Array.fromAsync(arrayLike)
Array.fromAsync(asyncIterable, mapFn)
Array.fromAsync(asyncIterable, mapFn, thisArg)
パラメータの説明
asyncIterable: 非同期反復可能オブジェクト(非同期ジェネレータなど)iterable: 反復可能オブジェクト(配列、文字列、Set など)arrayLike: 配列ライクオブジェクト(length プロパティとインデックス付き要素を持つオブジェクト)mapFn(省略可能): 各要素に対して呼び出されるマッピング関数thisArg(省略可能): mapFn を実行する際に this として使用される値
戻り値
新しい配列に解決される Promise を返します。
ブラウザサポート
Array.fromAsync() は比較的新しい機能であり、現在(2023年時点)では新しいバージョンのブラウザでのみサポートされています:
- Chrome 117+
- Firefox 115+
- Safari 16.4+
- Node.js 21+
サポートされていない環境では、polyfill を使用するか、同様の機能を自分で実装できます。
表内の数字は、このメソッドをサポートする最初のブラウザバージョン番号を表します。
| メソッド | |||||
|---|---|---|---|---|---|
| fromAsync() | 117+ | 121+ | 115+ | 16.4+ | 81.0+ |
使用例
例 1: 非同期ジェネレータから配列を作成
例
yield 1;
yield 2;
yield 3;
}
(async () => {
const result = await Array.fromAsync(asyncGenerator());
console.log(result); // 出力: [1, 2, 3]
})();
例 2: 通常の反復可能オブジェクトから配列を作成
例
(async () => {
const result = await Array.fromAsync(set);
console.log(result); // 出力: [1, 2, 3]
})();
例 3: マッピング関数を使用
例
yield 1;
yield 2;
yield 3;
}
(async () => {
const result = await Array.fromAsync(asyncNumbers(), x => x * 2);
console.log(result); // 出力: [2, 4, 6]
})();
Array.from() との違い
Array.fromAsync() と Array.from() はよく似ていますが、いくつかの重要な違いがあります:
1. 非同期データソースの処理
Array.fromAsync() は非同期反復可能オブジェクトを処理できますが、Array.from() はできません。
2. 戻り値
Array.from() は配列を直接返しますが、Array.fromAsync() は Promise を返します。
3. 実行タイミング
Array.from() は同期的に実行されますが、Array.fromAsync() は非同期的に実行されます。
実際の適用シナリオ
シナリオ 1: ページネーション API データの処理
例
let page = 1;
while (true) {
const response = await fetch(`https://api.example.com/data?page=${page}`);
const data = await response.json();
if (data.length === 0) break;
yield* data;
page++;
}
}
(async () => {
const allData = await Array.fromAsync(paginatedFetcher());
console.log(allData); // すべてのページのデータを1つの配列に結合
})();
シナリオ 2: 複数の非同期操作の結果を処理
例
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3)
];
(async () => {
const results = await Array.fromAsync(promises);
console.log(results); // 出力: [1, 2, 3]
})();
まとめ
Array.fromAsync() は、非同期データコレクションの処理に特に適した強力なツールです。非同期データソースから配列を作成するプロセスを簡素化し、コードをより明確で保守しやすくします。現在のところブラウザのサポートはまだ広くありませんが、時間の経過とともに非同期データコレクションを処理する標準的な方法の1つになるでしょう。
非同期データソースから配列を作成する必要があるときは、Array.fromAsync() が頼りになる助っ人です!
その他の拡張
JavaScript Array オブジェクト