Fetch API その1

ボタンを押すと fetch() を使って API にリクエストが投げます。 返ってきた JSON をパースした後、alert() で表示します。
ごく普通の実装です。fetch() は 2xx 以外のレスポンスコードが返っても、Promise.reject() してくれません。

ソースコード

// レスポンスに対して共通で行う前処理
var prepare = function(response) {
  // ステータスコードとステータステキストを表示
  console.info('ok?: ', response.ok);
  console.info('status: ', response.status);
  console.info('statusText: ', response.statusText);

  // レスポンスボディをJSONとしてパース
  return response.json();
}

// 正常終了時の処理
var onFulfilled = function(data) {
  var message = ([
    '成功ハンドラで処理されました。',
    'data: ' + JSON.stringify(data, null, '  '),
  ]).join('\n');

  console.log(data);
  alert(message);
};

// エラー終了時の処理
var onRejected = function(err) {
  var message = ([
    '失敗ハンドラで処理されました。',
    'error: ' + err.message,
  ]).join('\n');

  console.error(err);
  alert(message);
};

fetch('/path/to/api')
  .then(prepare)
  .then(onFulfilled)
  .catch(onRejected);