JavaScriptの非同期処理はWebアプリ開発に必須の知識です。API呼び出し・ファイル読み込みなど、結果を待つ処理をどう扱うかを理解しましょう。
なぜ非同期処理が必要か
JavaScriptはシングルスレッドで動作します。APIからデータを取得する間、処理を止めずに他の操作を受け付けるために非同期処理が必要です。
コールバック(古い方法)
// コールバック地獄の例
fetchUser(userId, function(user) {
fetchPosts(user.id, function(posts) {
fetchComments(posts[0].id, function(comments) {
console.log(comments); // ネストが深くなる
});
});
});
Promise(ES6〜)
// Promiseの基本
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve('成功!');
} else {
reject(new Error('失敗...'));
}
}, 1000);
});
promise
.then(result => console.log(result))
.catch(error => console.error(error));
// Promiseチェーン
fetchUser(userId)
.then(user => fetchPosts(user.id))
.then(posts => fetchComments(posts[0].id))
.then(comments => console.log(comments))
.catch(error => console.error(error));
// Promise.all(複数の非同期処理を並列実行)
const [users, products] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/products').then(r => r.json())
]);
async/await(最もモダンな書き方)
// async関数内でawaitが使える
async function getUserData(userId) {
try {
const user = await fetchUser(userId);
const posts = await fetchPosts(user.id);
const comments = await fetchComments(posts[0].id);
return comments;
} catch (error) {
console.error('エラー:', error.message);
throw error;
}
}
// 呼び出し
userGetData(1).then(comments => console.log(comments));
// またはasync関数内でawait
const comments = await getUserData(1);
fetch APIでWeb APIを呼ぶ
// GETリクエスト
async function getUsers() {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const users = await response.json();
return users;
}
// POSTリクエスト(データ送信)
async function createUser(userData) {
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData),
});
return response.json();
}
// 使い方
try {
const users = await getUsers();
console.log(users);
} catch (error) {
console.error('取得失敗:', error);
}
よくあるミス
- awaitをasync関数の外で使う(エラーになる)
- エラーハンドリングを忘れる(try/catchを必ず使う)
- Promise.allとawaitの混同(並列処理はPromise.all)
まとめ
JavaScriptの非同期処理はasync/await + try/catchの組み合わせが最もシンプルで読みやすい書き方です。fetch APIを使ったAPI呼び出しを実際に書いて手を動かしながら覚えましょう。
📚 プログラミング初心者におすすめの本