1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

アロー関数で、promiseの.then()と.catch()の使い方について

Last updated at Posted at 2025-07-12

JavaScriptのアロー関数とPromiseの.then().catch()についてまとめました。

アロー関数について

アロー関数は、従来の関数宣言をより簡潔に書ける:

// 従来の関数
function add(a, b) {
  return a + b;
}

// アロー関数
const add = (a, b) => a + b;

.then()メソッド

.then()はPromiseが成功(resolve)した時に実行される処理を定義します。

// 基本的な使い方
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data));

// 複数のthenをチェーン
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log('データを取得しました:', data);
    return data.processedData;
  })
  .then(processedData => {
    console.log('処理済みデータ:', processedData);
  });

.catch()メソッド

.catch()はPromiseが失敗(reject)した時や、エラーが発生した時に実行される処理を定義します。

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    console.error('エラーが発生しました:', error);
  });

アロー関数と組み合わせた例

// 非同期処理の例
const fetchUserData = (userId) => {
  return fetch(`/api/users/${userId}`)
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
    })
    .then(userData => {
      console.log('ユーザー情報:', userData);
      return userData;
    })
    .catch(error => {
      console.error('ユーザー情報の取得に失敗:', error);
      throw error; // エラーを再度投げる
    });
};

// 使用例
fetchUserData(123)
  .then(user => {
    document.getElementById('username').textContent = user.name;
  })
  .catch(error => {
    document.getElementById('error').textContent = 'データの読み込みに失敗しました';
  });

重要なポイント

エラーハンドリングの流れ

  • .then()チェーンの途中でエラーが発生すると、次の.catch()まで処理がスキップされます
  • .catch()でエラーを処理した後、新しい値を返すことで処理を継続できます

返り値

  • .then().catch()は常に新しいPromiseを返すため、メソッドチェーンが可能です
  • 値を返さない場合はundefinedを返すPromiseになります

async/awaitとの比較

// .then()/.catch()を使用
const getData = () => {
  return fetch('/api/data')
    .then(response => response.json())
    .catch(error => console.error(error));
};

// async/awaitを使用(同じ処理)
const getData = async () => {
  try {
    const response = await fetch('/api/data');
    return await response.json();
  } catch (error) {
    console.error(error);
  }
};

async/awaitの方が読みやすい場合が多いそうだ。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?