--- title: Promise.prototype.then() slug: Web/JavaScript/Reference/Global_Objects/Promise/then tags: - ECMAScript6 - JavaScript - Method - Promise - Prototype - Referensi translation_of: Web/JavaScript/Reference/Global_Objects/Promise/then ---
{{JSRef}}

Method then() mengembalikan {{domxref("Promise")}}. Menggunakan dua argumen: fungsi callback untuk kasus sukses dan gagal pada Promise.

Sintaks

p.then(onFulfilled, onRejected);

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

Parameter

onFulfilled
{{jsxref("Function")}} dipanggil ketika Promise dipenuhi. Fungsi ini memiliki satu argumen, value pemenuhan.
onRejected
{{jsxref("Function")}} dipangil ketika Promise ditolak. fungsi ini memiliki satau argumen, alasan penolakan.

Deskripsi

Kedua method then dan {{jsxref("Promise.prototype.catch()")}} megembalikan promis, juga dapat dirantaikan — operasi yang disebut composition.

Contoh

Meggunakan method 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!
});

Perantaian

Karena method then mengembalikan Promise, anda bisa merantaikan pemanggilan 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
});

Anda juga bisa menggunakan perantaian untuk melaksanakan satu fungsi dengan sebuah Promise berbasis API diatas fungsi lainnya.

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()
  });
}

Spesifikasi

Spesifikasi Status Comment
{{SpecName('ES6', '#sec-promise.prototype.then', 'Promise.prototype.then')}} {{Spec2('ES6')}} Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.then', 'Promise.prototype.then')}} {{Spec2('ESDraft')}}  

Kompabilitas Browser

{{Compat("javascript.builtins.Promise.then")}}

 

Lihat juga