JavaScript•非同期プログラミング
JavaScriptの Async/Await、Promise、Promise.all
Node.js のイベントループがノンブロッキング I/O を扱う仕組みと、async/await で同期コードのように読みやすく書く方法を学びます。
構文
async function fetchVal() {
const res = await promise;
return res;
}
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| async function | Declaration | 暗黙的に Promise を返します。 |
| await | Operator | Promise が確定するまで async 関数の実行を一時停止します。 |
| Promise.all() | Static Method | 複数の Promise を並列実行します。 |
そのまま実行できるコード例
Compilra で実行可能JavaScript をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
// Asynchronous Programming with Promises and Async/Await
const simulateApiCall = (service, delayMs) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ service: service, status: "SUCCESS", timeMs: delayMs });
}, delayMs);
});
};
async function loadApplicationData() {
console.log("--- Starting Parallel Requests ---");
const startTime = Date.now();
// Run calls in parallel using Promise.all
const results = await Promise.all([
simulateApiCall("User-Profile", 30),
simulateApiCall("Notifications", 20),
simulateApiCall("Metrics", 40)
]);
results.forEach(res => {
console.log("Loaded " + res.service + " in " + res.timeMs + "ms");
});
console.log("All services loaded concurrently!");
}
loadApplicationData();期待される出力:
--- Starting Parallel Requests --- Loaded User-Profile in 30ms Loaded Notifications in 20ms Loaded Metrics in 40ms All services loaded concurrently!
動作のしくみ: ステップ解説
- 2〜8行目: setTimeout でノンブロッキングネットワーク I/O を模擬する Promise を作成します。
- 15〜19行目: Promise.all により3つのリクエストを順番ではなく同時に開始します。
- 21〜23行目: await された結果がレスポンス配列として展開されます。
重要ポイント
- async 関数はプリミティブ値を返す場合でも常に Promise を返します。
- await は async 関数内の実行だけを一時停止し、イベントループ自体はブロックしません。
- 独立した並列処理には Promise.all、順次処理には for...of と await を使いましょう。
よくある間違い: 独立したタスクに対して Promise.all を使わずループ内で順番に await すること
ループ内で await するとタスクが1つずつ実行され、待ち時間が何倍にも増えてしまいます。
❌ 誤り
for (const id of ids) { await fetchItem(id); } // Sequential slowdown!✅ 正しい例
await Promise.all(ids.map(id => fetchItem(id))); // Runs all concurrently
関連するJavaScriptチュートリアルとコンパイラ
Compilra で JavaScript を実行・テストする
Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。