Async functions
async/await は Promise を基盤とした糖衣構文です。async 関数は常に Promise を返し、await キーワードで Promise の解決を待機できます。try/catch でのエラーハンドリングも自然に書けます。
概要
async/await は Promise を基盤とした糖衣構文です。async 関数は常に Promise を返し、await キーワードで Promise の解決を待機できます。try/catch でのエラーハンドリングも自然に書けます。
対応ブラウザ
| 機能 | デスクトップ | モバイル | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 55 | 15 | 52 | 10.1 | 55 | 10.3 | |
| AsyncFunction() コンストラクターは AsyncFunction オブジェクトを生成します。 | 55 | 15 | 52 | 10.1 | 55 | 10.3 |
| その他 | ||||||
| async function キーワードは、式の中で非同期関数を定義するために使用できます。 | 55 | 15 | 52 | 10.1 | 55 | 10.3 |
| await 演算子はプロミス (Promise) を待ち、履行値を取得するために使用します。非同期関数の中、またはモジュールの最上位でのみ使用することができます。 | 55 | 14 | 52 | 10.1 | 55 | 10.3 |
| async function 宣言は、与えられた名前で新しい非同期関数のbindingを作成します。その関数の本体の中では await キーワードを使うことができ、ます。async および await キーワードを使用することで、プロミスベースの非同期の動作を、プロミスチェーンを明示的に構成する必要なく、よりすっきりとした方法で書くことができます。 | 55 | 15 | 52 | 10.1 | 55 | 10.3 |
基本構文
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error('Failed to retrieve');
const user = await response.json();
return user;
} catch (error) {
console.error('Error:', error.message);
}
}
// Top-level await (ES modules)
const data = await fetchUserData(1); ライブデモ
Sequential async flow
Await three steps in order and compare the output with the order written in the source.
try/catch around awaited work
Handle successful and failing Promises with one control-flow structure.
実務での使いどころ
-
Async functions の活用
Promise ベースの非同期処理を同期的な書き方で記述できる構文。コードの可読性を大幅に向上させる。
注意点
- 特になし。すべての主要ブラウザで安定して動作する。
アクセシビリティ
- JavaScript による動的更新時は、aria-live リージョンで変更をスクリーンリーダーに通知する。
参考リンク
Powered by web-features