Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Promise.prototype.then()

この記事は編集レビューを必要としています。ぜひご協力ください

この翻訳は不完全です。英語から この記事を翻訳 してください。

then()メソッドはPromiseを返します。2つの引数を持ち、両方ともPromiseが成功した場合、失敗した場合のコールバック関数です。

構文

p.then(onFulfilled, onRejected);

p.then(function(value) {
   // fulfillment
  }, function(reason) {
  // rejection
});

引数

onFulfilled
Promiseが成功したとき呼ばれるFunction。この関数は1つの引数、valueを持ちます。
onRejected
Promiseが失敗したとき呼ばれるFunction。この関数は1つの引数、reasonを持ちます。

説明

thenメソッドとPromise.prototype.catch()メソッドはプロミスを返して、チェーンされます。 — compositionと呼ばれる操作。

then メソッドを使う

var p1 = new Promise(function(resolve, reject) {
  resolve("Success!");
  // or
  // reject ("Error!");
});

p1.then(function(value) {
  console.log(value); // Success!
}, function(reason) {
  console.log(reason); // Error!
});

チェーン

then メソッドはPromiseを返すので、thenの呼び出しを簡単に繋げます。

var p2 = new Promise(function(resolve, reject) {
  resolve(1);
});

p2.then(function(value) {
  console.log(value); // 1
  return value + 1;
}).then(function(value) {
  console.log(value); // 2
});

p2.then(function(value) {
  console.log(value); // 1
});

同様に、別の関数上にプロミスベースのAPIとともに関数を実装することでチェーンを使うこともできます。

function fetch_current_data() {
  // The fetch() API returns a Promise.  This function
  // exposes a similar API, except the fulfillment
  // value of this function's Promise has had more
  // work done on it.
  return fetch("current-data.json").then((response) => {
    if (response.headers.get("content-type") != "application/json") {
      throw new TypeError();
    }
    var j = response.json();
    // maybe do something with j
    return j; // fulfillment value given to user of
              // fetch_current_data().then()
  });
}

仕様

仕様 状況 コメント
ECMAScript 2015 (6th Edition, ECMA-262)
Promise.prototype.then の定義
標準 ECMA標準における初期定義
ECMAScript 2017 Draft (ECMA-262)
Promise.prototype.then の定義
ドラフト  

ブラウザ実装状況

機能 Chrome Firefox (Gecko) Internet Explorer Opera Safari
基本サポート 32 29.0 (29.0) 未サポート 19 7.1
機能 Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
基本サポート 未サポート 29.0 (29.0) 未サポート 未サポート 8 32

関連情報

ドキュメントのタグと貢献者

 このページの貢献者: akiomik, shide55
 最終更新者: akiomik,