diff options
Diffstat (limited to 'files/id/web/javascript/reference/global_objects/promise')
5 files changed, 797 insertions, 0 deletions
diff --git a/files/id/web/javascript/reference/global_objects/promise/catch/index.html b/files/id/web/javascript/reference/global_objects/promise/catch/index.html new file mode 100644 index 0000000000..f2d5e38e8f --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,127 @@ +--- +title: Promise.prototype.catch() +slug: Web/JavaScript/Reference/Global_Objects/Promise/catch +tags: + - ECMAScript6 + - Method + - Promise + - Prototype + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch +--- +<div>{{JSRef}}</div> + +<p>Method <strong>catch()</strong> mengembalikan <code>Promise</code> dan hanya setuju jika kasusnya gagal. Sama halnya dengan memenggil method {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}}.</p> + +<h2 id="Sintaks">Sintaks</h2> + +<pre class="syntaxbox"><var>p.catch(onRejected)</var>; + +p.catch(function(reason) { + // rejection +}); +</pre> + +<h3 id="Parameter">Parameter</h3> + +<dl> + <dt>onRejected</dt> + <dd> {{jsxref("Function")}} dipanggil ketika <code>Promise</code> ditolak. Fungsi ini memiliki satu argumen, alasan penolakan.</dd> +</dl> + +<h2 id="Deskripsi">Deskripsi</h2> + +<p>Method <code>catch</code> sangat berguna untuk menangani error di gabungan promis anda.</p> + +<h2 id="Contoh">Contoh</h2> + +<h3 id="Penggunaan_method_catch">Penggunaan method <code>catch</code></h3> + +<pre class="brush: js">var p1 = new Promise(function(resolve, reject) { + resolve('Success'); +}); + +p1.then(function(value) { + console.log(value); // "Success!" + throw 'oh, no!'; +}).catch(function(e) { + console.log(e); // "oh, no!" +}).then(function(){ + console.log('after a catch the chain is restored'); +}, function () { + console.log('Not fired due to the catch'); +}); + +// The following behaves the same as above +p1.then(function(value) { + console.log(value); // "Success!" + return Promise.reject('oh, no!'); +}).catch(function(e) { + console.log(e); // "oh, no!" +}).then(function(){ + console.log('after a catch the chain is restored'); +}, function () { + console.log('Not fired due to the catch'); +}); + +</pre> + +<h3 id="Promis_tidak_dapat_mendeteksi_error_pada_asynchronous_callback">Promis tidak dapat mendeteksi error pada asynchronous callback</h3> + +<pre class="brush: js">var p1 = new Promise(function(resolve, reject) { + throw 'Uh-oh!'; +}); + +p1.catch(function(e) { + console.log(e); // "Uh-oh!" +}); + + +var p2 = new Promise(function(resolve, reject) { + setTimeout(function() { + throw 'Uncaught Exception!'; + }, 1000); +}); + +p2.catch(function(e) { + console.log(e); // This is never called +});</pre> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Kompabilitas_Browser">Kompabilitas Browser</h2> + +<p> </p> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Promise.catch")}}</p> + +<p> </p> + +<h2 id="Lihat_Juga">Lihat Juga</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.then()")}}</li> +</ul> diff --git a/files/id/web/javascript/reference/global_objects/promise/index.html b/files/id/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..240915ba23 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,317 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - ECMAScript6 + - JavaScript + - NeedsTranslation + - Promise + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>Promise</code></strong> object is used for deferred and asynchronous computations. A <code>Promise</code> represents an operation that hasn't completed yet, but is expected in the future.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">new Promise( /* executor */ function(resolve, reject) { ... } );</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt>executor</dt> + <dd>A function that will be passed to other functions via the arguments <code>resolve</code> and <code>reject</code>. The <code>executor</code> function is executed immediately by the Promise implementation which provides the <code>resolve</code> and <code>reject</code> functions (the executor is called before the <code>Promise</code> constructor even returns the created object). The <code>resolve</code> and <code>reject</code> functions are bound to the promise and calling them fulfills or rejects the promise, respectively. The executor is expected to initiate some asynchronous work and then, once that completes, call either the <code>resolve</code> or <code>reject</code> function to resolve the promise's final value or else reject it if an error occurred.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>A <code><strong>Promise</strong></code> represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a <em>promise</em> of having a value at some point in the future.</p> + +<p>A <code>Promise</code> is in one of these states:</p> + +<ul> + <li><em>pending</em>: initial state, not fulfilled or rejected.</li> + <li><em>fulfilled</em>: meaning that the operation completed successfully.</li> + <li><em>rejected</em>: meaning that the operation failed.</li> +</ul> + +<p>A pending promise can become either <em>fulfilled</em> with a value, or <em>rejected</em> with a reason (error). When either of these happens, the associated handlers queued up by a promise's <code>then</code> method are called. (If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.)</p> + +<p>As the <code>{{jsxref("Promise.then", "Promise.prototype.then()")}}</code> and <code>{{jsxref("Promise.catch", "Promise.prototype.catch()")}}</code> methods return promises, they can be chained—an operation called <em>composition</em>.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/8633/promises.png"></p> + +<div class="note"> +<p><strong>Note</strong>: A promise is said to be <em>settled </em>if it is either fulfilled or rejected, but not pending. You will also hear the term <em>resolved</em> used with promises — this means that the promise is settled, or it is locked into a promise chain. Domenic Denicola's <a href="https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md">States and fates</a> contains more details about promise terminology.</p> +</div> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Promise.length</code></dt> + <dd>Length property whose value is 1 (number of constructor arguments).</dd> + <dt>{{jsxref("Promise.prototype")}}</dt> + <dd>Represents the prototype for the <code>Promise</code> constructor.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("Promise.all", "Promise.all(iterable)")}}</dt> + <dd>Returns a promise that either resolves when all of the promises in the iterable argument have resolved or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise resolves, it is resolved with an array of the values from the resolved promises in the iterable. If the returned promise rejects, it is rejected with the reason from the promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises together.</dd> + <dt>{{jsxref("Promise.race", "Promise.race(iterable)")}}</dt> + <dd>Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.</dd> +</dl> + +<dl> + <dt>{{jsxref("Promise.reject", "Promise.reject(reason)")}}</dt> + <dd>Returns a <code>Promise</code> object that is rejected with the given reason.</dd> +</dl> + +<dl> + <dt>{{jsxref("Promise.resolve", "Promise.resolve(value)")}}</dt> + <dd>Returns a <code>Promise</code> object that is resolved with the given value. If the value is a thenable (i.e. has a <code>then</code> method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. Generally, if you want to know if a value is a promise or not - {{jsxref("Promise.resolve", "Promise.resolve(value)")}} it instead and work with the return value as a promise.</dd> +</dl> + +<h2 id="Promise_prototype"><code>Promise</code> prototype</h2> + +<h3 id="Properties_2">Properties</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}</p> + +<h3 id="Methods_2">Methods</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Creating_a_Promise">Creating a Promise</h3> + +<pre class="brush: html hidden"><button id="btn">Make a promise!</button> +<div id="log"></div> +</pre> + +<p>This small example shows the mechanism of a <code>Promise</code>. The <code>testPromise()</code> method is called each time the {{HTMLElement("button")}} is clicked. It creates a promise that will resolve, using {{domxref("window.setTimeout()")}}, to the promise count (number starting from 1) every 1-3 seconds, at random. The <code>Promise()</code> constructor is used to create the promise.</p> + +<p>The fulfillment of the promise is simply logged, via a fulfill callback set using {{jsxref("Promise.prototype.then()","p1.then()")}}. A few logs shows how the synchronous part of the method is decoupled of the asynchronous completion of the promise.</p> + +<pre class="brush: js">'use strict'; +var promiseCount = 0; + +function testPromise() { + var thisPromiseCount = ++promiseCount; + + var log = document.getElementById('log'); + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Started (<small>Sync code started</small>)<br/>'); + + // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s) + var p1 = new Promise( + // The resolver function is called with the ability to resolve or + // reject the promise + function(resolve, reject) { + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Promise started (<small>Async code started</small>)<br/>'); + // This is only an example to create asynchronism + window.setTimeout( + function() { + // We fulfill the promise ! + resolve(thisPromiseCount); + }, Math.random() * 2000 + 1000); + } + ); + + // We define what to do when the promise is resolved/fulfilled with the then() call, + // and the catch() method defines what to do if the promise is rejected. + p1.then( + // Log the fulfillment value + function(val) { + log.insertAdjacentHTML('beforeend', val + + ') Promise fulfilled (<small>Async code terminated</small>)<br/>'); + }) + .catch( + // Log the rejection reason + function(reason) { + console.log('Handle rejected promise ('+reason+') here.'); + }); + + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Promise made (<small>Sync code terminated</small>)<br/>'); +}</pre> + +<pre class="brush:js hidden">if ("Promise" in window) { + var btn = document.getElementById("btn"); + btn.addEventListener("click",testPromise); +} +else { + log = document.getElementById('log'); + log.innerHTML = "Live example not available as your browser doesn't support the <code>Promise<code> interface."; +} +</pre> + +<p>This example is executed when clicking the button. You need a browser supporting <code>Promise</code>. By clicking several times the button in a short amount of time, you'll even see the different promises being fulfilled one after the other.</p> + +<p>{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}</p> + +<h2 id="Example_using_new_XMLHttpRequest()">Example using new XMLHttpRequest()</h2> + +<h3 id="Creating_a_Promise_2">Creating a Promise</h3> + +<p>This example shows the implementation of a method which uses a <code>Promise</code> to report the success or failure of an {{domxref("XMLHttpRequest")}}.</p> + +<pre class="brush: js">'use strict'; + +// A-> $http function is implemented in order to follow the standard Adapter pattern +function $http(url){ + + // A small example of object + var core = { + + // Method that performs the ajax request + ajax : function (method, url, args) { + + // Creating a promise + var promise = new Promise( function (resolve, reject) { + + // Instantiates the XMLHttpRequest + var client = new XMLHttpRequest(); + var uri = url; + + if (args && (method === 'POST' || method === 'PUT')) { + uri += '?'; + var argcount = 0; + for (var key in args) { + if (args.hasOwnProperty(key)) { + if (argcount++) { + uri += '&'; + } + uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]); + } + } + } + + client.open(method, uri); + client.send(); + + client.onload = function () { + if (this.status >= 200 && this.status < 300) { + // Performs the function "resolve" when this.status is equal to 2xx + resolve(this.response); + } else { + // Performs the function "reject" when this.status is different than 2xx + reject(this.statusText); + } + }; + client.onerror = function () { + reject(this.statusText); + }; + }); + + // Return the promise + return promise; + } + }; + + // Adapter pattern + return { + 'get' : function(args) { + return core.ajax('GET', url, args); + }, + 'post' : function(args) { + return core.ajax('POST', url, args); + }, + 'put' : function(args) { + return core.ajax('PUT', url, args); + }, + 'delete' : function(args) { + return core.ajax('DELETE', url, args); + } + }; +}; +// End A + +// B-> Here you define its functions and its payload +var mdnAPI = 'https://developer.mozilla.org/en-US/search.json'; +var payload = { + 'topic' : 'js', + 'q' : 'Promise' +}; + +var callback = { + success : function(data){ + console.log(1, 'success', JSON.parse(data)); + }, + error : function(data){ + console.log(2, 'error', JSON.parse(data)); + } +}; +// End B + +// Executes the method call +$http(mdnAPI) + .get(payload) + .then(callback.success) + .catch(callback.error); + +// Executes the method call but an alternative way (1) to handle Promise Reject case +$http(mdnAPI) + .get(payload) + .then(callback.success, callback.error); + +// Executes the method call but an alternative way (2) to handle Promise Reject case +$http(mdnAPI) + .get(payload) + .then(callback.success) + .then(undefined, callback.error); +</pre> + +<h3 id="Loading_an_image_with_XHR">Loading an image with XHR</h3> + +<p>Another simple example using <code>Promise</code> and <code><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></code> to load an image is available at the MDN GitHub<a href="https://github.com/mdn/promises-test/blob/gh-pages/index.html"> promise-test</a> repository. You can also <a href="http://mdn.github.io/promises-test/">see it in action</a>. Each step is commented and allows you to follow the Promise and XHR architecture closely.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p> </p> + +<div> + + +<p>{{Compat("javascript.builtins.Promise")}}</p> +</div> + +<p> </p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="http://promisesaplus.com/">Promises/A+ specification</a></li> + <li><a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Jake Archibald: JavaScript Promises: There and Back Again</a></li> + <li><a href="http://de.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript">Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript</a></li> + <li><a href="http://www.mattgreer.org/articles/promises-in-wicked-detail/">Matt Greer: JavaScript Promises ... In Wicked Detail</a></li> + <li><a href="https://www.promisejs.org/">Forbes Lindesay: promisejs.org</a></li> + <li><a href="http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html">Nolan Lawson: We have a problem with promises — Common mistakes with promises</a></li> + <li><a href="https://github.com/jakearchibald/es6-promise/">Promise polyfill</a></li> +</ul> diff --git a/files/id/web/javascript/reference/global_objects/promise/reject/index.html b/files/id/web/javascript/reference/global_objects/promise/reject/index.html new file mode 100644 index 0000000000..180fcc5571 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/reject/index.html @@ -0,0 +1,81 @@ +--- +title: Promise.reject() +slug: Web/JavaScript/Reference/Global_Objects/Promise/reject +tags: + - ECMAScript6 + - Method + - Promise + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/reject +--- +<div>{{JSRef}}</div> + +<p>Method <code><strong>Promise.reject(reason)</strong></code> mengembalikan objek <code>Promise</code> yang ditolak dengan alasan yang diberikan.</p> + +<h2 id="Sintaks">Sintaks</h2> + +<pre class="syntaxbox"><var>Promise.reject(reason)</var>;</pre> + +<h3 id="Parameter">Parameter</h3> + +<dl> + <dt>reason</dt> + <dd>Alasan kenapa <code>Promise</code> ditolak.</dd> +</dl> + +<h2 id="Deskripsi">Deskripsi</h2> + +<p>Fungsi static <code>Promise.reject</code> mengembalikan <code>Promise</code> yang ditolak. Untuk keperluan debugging dan seleksi penankapan error, sangat berguna untuk membuat <code>reason</code> pada <code>instanceof</code> {{jsxref("Error")}}.</p> + +<h2 id="Contoh">Contoh</h2> + +<h3 id="Penggunaan_mthod_static_Promise.reject()">Penggunaan mthod static Promise.reject()</h3> + +<pre class="brush: js">Promise.reject("Testing static reject").then(function(reason) { + // not called +}, function(reason) { + console.log(reason); // "Testing static reject" +}); + +Promise.reject(new Error("fail")).then(function(error) { + // not called +}, function(error) { + console.log(error); // Stacktrace +});</pre> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.reject', 'Promise.reject')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.reject', 'Promise.reject')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Kompabilitas_Browser">Kompabilitas Browser</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Promise.reject")}}</p> + +<p> </p> + +<h2 id="Lihat_Juga">Lihat Juga</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li><a href="https://github.com/petkaantonov/bluebird#error-handling">Selective error catching using the BlueBird Promise library</a></li> +</ul> diff --git a/files/id/web/javascript/reference/global_objects/promise/resolve/index.html b/files/id/web/javascript/reference/global_objects/promise/resolve/index.html new file mode 100644 index 0000000000..d958ab4d52 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/resolve/index.html @@ -0,0 +1,140 @@ +--- +title: Promise.resolve() +slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve +tags: + - ECMAScript6 + - JavaScript + - Method + - Promise +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/resolve +--- +<div>{{JSRef}}</div> + +<p>Method <code><strong>Promise.resolve(value)</strong></code> mengembalikan objek {{jsxref("Promise.then")}} yang diselesaikan dengan nilai yang diberikan. jika nilainya thenable (mis. memiliki {{jsxref("Promise.then", "\"then\" method")}}), promise yang dikembalikan akan "mengikuti" thenable-nya, menggunakan keadaan ini; sebaliknya promise akan dikembalikan sesuai nilai yang terpenuhi.</p> + +<h2 id="Sintaks">Sintaks</h2> + +<pre class="syntaxbox"><var>Promise.resolve(value)</var>; +Promise.resolve(promise); +Promise.resolve(thenable); +</pre> + +<h3 id="Parameter">Parameter</h3> + +<dl> + <dt>value</dt> + <dd>Argumen untuk diselesaikan oleh <code>Promise</code>. Dapat juga sebuah <code>Promise</code> atau thenable untuk diselesaikan.</dd> +</dl> + +<h2 id="Deskripsi">Deskripsi</h2> + +<p>Fungsi statis <code>Promise.resolve</code> mengembalikan <code>Promise</code> yang terselesaikan.</p> + +<h2 id="Contoh">Contoh</h2> + +<h3 id="Penggunaan_method_static_Promise.resolve">Penggunaan method static <code>Promise.resolve</code></h3> + +<pre class="brush: js">Promise.resolve("Success").then(function(value) { + console.log(value); // "Success" +}, function(value) { + // not called +}); +</pre> + +<h3 id="Penyelesaian_pada_array">Penyelesaian pada array</h3> + +<pre class="brush: js">var p = Promise.resolve([1,2,3]); +p.then(function(v) { + console.log(v[0]); // 1 +}); +</pre> + +<h3 id="Penyelesaian_pada_Promise_lain">Penyelesaian pada <code>Promise </code>lain</h3> + +<pre class="brush: js">var original = Promise.resolve(true); +var cast = Promise.resolve(original); +cast.then(function(v) { + console.log(v); // true +}); +</pre> + +<h3 id="Penyelesaian_thenables_dan_throwing_Errors">Penyelesaian thenables dan throwing Errors</h3> + +<pre class="brush: js">// Resolving a thenable object +var p1 = Promise.resolve({ + then: function(onFulfill, onReject) { onFulfill("fulfilled!"); } +}); +console.log(p1 instanceof Promise) // true, object casted to a Promise + +p1.then(function(v) { + console.log(v); // "fulfilled!" + }, function(e) { + // not called +}); + +// Thenable throws before callback +// Promise rejects +var thenable = { then: function(resolve) { + throw new TypeError("Throwing"); + resolve("Resolving"); +}}; + +var p2 = Promise.resolve(thenable); +p2.then(function(v) { + // not called +}, function(e) { + console.log(e); // TypeError: Throwing +}); + +// Thenable throws after callback +// Promise resolves +var thenable = { then: function(resolve) { + resolve("Resolving"); + throw new TypeError("Throwing"); +}}; + +var p3 = Promise.resolve(thenable); +p3.then(function(v) { + console.log(v); // "Resolving" +}, function(e) { + // not called +}); +</pre> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.resolve', 'Promise.resolve')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.resolve', 'Promise.resolve')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Kompabilitas_Browser">Kompabilitas Browser</h2> + +<p> </p> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Promise.resolve")}}</p> + +<p> </p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> +</ul> diff --git a/files/id/web/javascript/reference/global_objects/promise/then/index.html b/files/id/web/javascript/reference/global_objects/promise/then/index.html new file mode 100644 index 0000000000..5a1e275c8c --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/then/index.html @@ -0,0 +1,132 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>Method <code><strong>then()</strong></code> mengembalikan {{domxref("Promise")}}. Menggunakan dua argumen: fungsi callback untuk kasus sukses dan gagal pada <code>Promise</code>.</p> + +<h2 id="Sintaks">Sintaks</h2> + +<pre class="syntaxbox"><var>p.then(onFulfilled, onRejected)</var>; + +p.then(function(value) { + // fulfillment + }, function(reason) { + // rejection +}); +</pre> + +<h3 id="Parameter">Parameter</h3> + +<dl> + <dt><code>onFulfilled</code></dt> + <dd>{{jsxref("Function")}} dipanggil ketika <code>Promise</code> dipenuhi. Fungsi ini memiliki satu argumen, <code>value pemenuhan</code>.</dd> + <dt><code>onRejected</code></dt> + <dd>{{jsxref("Function")}} dipangil ketika <code>Promise</code> ditolak. fungsi ini memiliki satau argumen, alasan penolakan.</dd> +</dl> + +<h2 id="Deskripsi">Deskripsi</h2> + +<p>Kedua method <code>then</code> dan {{jsxref("Promise.prototype.catch()")}} megembalikan promis, juga dapat dirantaikan — operasi yang disebut <em>composition</em>.</p> + +<h2 id="Contoh">Contoh</h2> + +<h3 id="Meggunakan_method_then">Meggunakan method <code>then</code></h3> + +<pre class="brush: js">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! +}); +</pre> + +<h3 id="Perantaian">Perantaian</h3> + +<p>Karena method <code>then</code> mengembalikan <code>Promise</code>, anda bisa merantaikan pemanggilan <code>then</code>.</p> + +<pre class="brush: js">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 +}); +</pre> + +<p>Anda juga bisa menggunakan perantaian untuk melaksanakan satu fungsi dengan sebuah Promise berbasis API diatas fungsi lainnya.</p> + +<pre class="brush: js">function fetch_current_data() { + // The <a href="/en-US/docs/Web/API/GlobalFetch/fetch">fetch</a>() 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() + }); +} +</pre> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.prototype.then', 'Promise.prototype.then')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype.then', 'Promise.prototype.then')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Kompabilitas_Browser">Kompabilitas Browser</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Promise.then")}}</p> + +<p> </p> + +<h2 id="Lihat_juga">Lihat juga</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.catch()")}}</li> +</ul> |