--- 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 ---
Method then() mengembalikan {{domxref("Promise")}}. Menggunakan dua argumen: fungsi callback untuk kasus sukses dan gagal pada Promise.
p.then(onFulfilled, onRejected);
p.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
onFulfilledPromise dipenuhi. Fungsi ini memiliki satu argumen, value pemenuhan.onRejectedPromise ditolak. fungsi ini memiliki satau argumen, alasan penolakan.Kedua method then dan {{jsxref("Promise.prototype.catch()")}} megembalikan promis, juga dapat dirantaikan — operasi yang disebut composition.
thenvar 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!
});
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 | 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')}} |
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
{{Compat("javascript.builtins.Promise.then")}}