diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:43:23 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:43:23 -0500 |
commit | 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch) | |
tree | a9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/tr/web/javascript/reference/global_objects/promise | |
parent | 074785cea106179cb3305637055ab0a009ca74f2 (diff) | |
download | translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2 translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip |
initial commit
Diffstat (limited to 'files/tr/web/javascript/reference/global_objects/promise')
3 files changed, 752 insertions, 0 deletions
diff --git a/files/tr/web/javascript/reference/global_objects/promise/all/index.html b/files/tr/web/javascript/reference/global_objects/promise/all/index.html new file mode 100644 index 0000000000..cc57749d77 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/promise/all/index.html @@ -0,0 +1,234 @@ +--- +title: Promise.all() +slug: Web/JavaScript/Reference/Global_Objects/Promise/all +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>Promise.all()</code></strong> method returns a single {{jsxref("Promise")}} that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.</p> + +<div>{{EmbedInteractiveExample("pages/js/promise-all.html")}}</div> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="Söz_dizimi">Söz dizimi</h2> + +<pre class="syntaxbox">Promise.all(<var>iterable</var>);</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd>{{jsxref("Array")}} yada {{jsxref("String")}} gibi <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">iterable</a> nesnesi.</dd> +</dl> + +<h3 id="Dönen_değer">Dönen değer</h3> + +<ul> + <li>An <strong>already resolved</strong> {{jsxref("Promise")}} if the <var>iterable</var> passed is empty.</li> + <li>An <strong>asynchronously resolved</strong> {{jsxref("Promise")}} if the <var>iterable</var> passed contains no promises. Note, Google Chrome 58 returns an <strong>already resolved</strong> promise in this case.</li> + <li>A <strong>pending</strong> {{jsxref("Promise")}} in all other cases. This returned promise is then resolved/rejected <strong>asynchronously</strong> (as soon as the stack is empty) when all the promises in the given <var>iterable</var> have resolved, or if any of the promises reject. See the example about "Asynchronicity or synchronicity of Promise.all" below. Returned values will be in order of the Promises passed, regardless of completion order.</li> +</ul> + +<h2 id="Açıklama">Açıklama</h2> + +<p>This method can be useful for aggregating the results of multiple promises.</p> + +<h3 id="Fulfillment">Fulfillment</h3> + +<p>The returned promise is fulfilled with an array containing <strong>all </strong>the values of the <var>iterable</var> passed as argument (also non-promise values).</p> + +<ul> + <li>If an empty <var>iterable</var> is passed, then this method returns (synchronously) an already resolved promise.</li> + <li>If all of the passed-in promises fulfill, or are not promises, the promise returned by <code>Promise.all</code> is fulfilled asynchronously.</li> +</ul> + +<h3 id="Rejection">Rejection</h3> + +<p>If any of the passed-in promises reject, <code>Promise.all</code> asynchronously rejects with the value of the promise that rejected, whether or not the other promises have resolved.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Promise.all_Kullanımı"><code>Promise.all</code> Kullanımı</h3> + +<p><code>Promise.all</code> tüm işlemler yerine getirilene kadar bekler (yada ilk reddedilmeye kadar).</p> + +<pre class="brush: js">var p1 = Promise.resolve(3); +var p2 = 1337; +var p3 = new Promise((resolve, reject) => { + setTimeout(() => { + resolve("foo"); + }, 100); +}); + +Promise.all([p1, p2, p3]).then(values => { + console.log(values); // [3, 1337, "foo"] +});</pre> + +<p>If the <var>iterable</var> contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled):</p> + +<pre class="brush: js">// this will be counted as if the iterable passed is empty, so it gets fulfilled +var p = Promise.all([1,2,3]); +// this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled +var p2 = Promise.all([1,2,3, Promise.resolve(444)]); +// this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected +var p3 = Promise.all([1,2,3, Promise.reject(555)]); + +// using setTimeout we can execute code after the stack is empty +setTimeout(function() { + console.log(p); + console.log(p2); + console.log(p3); +}); + +// logs +// Promise { <state>: "fulfilled", <value>: Array[3] } +// Promise { <state>: "fulfilled", <value>: Array[4] } +// Promise { <state>: "rejected", <reason>: 555 }</pre> + +<h3 id="Asynchronicity_or_synchronicity_of_Promise.all">Asynchronicity or synchronicity of <code>Promise.all</code></h3> + +<p>This following example demonstrates the asynchronicity (or synchronicity, if the <var>iterable</var> passed is empty) of <code>Promise.all</code>:</p> + +<pre class="brush: js">// we are passing as argument an array of promises that are already resolved, +// to trigger Promise.all as soon as possible +var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; + +var p = Promise.all(resolvedPromisesArray); +// immediately logging the value of p +console.log(p); + +// using setTimeout we can execute code after the stack is empty +setTimeout(function() { + console.log('the stack is now empty'); + console.log(p); +}); + +// logs, in order: +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: Array[2] } +</pre> + +<p>The same thing happens if <code>Promise.all</code> rejects:</p> + +<pre class="brush: js">var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)]; +var p = Promise.all(mixedPromisesArray); +console.log(p); +setTimeout(function() { + console.log('the stack is now empty'); + console.log(p); +}); + +// logs +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "rejected", <reason>: 44 } +</pre> + +<p>But, <code>Promise.all</code> resolves synchronously <strong>if and only if</strong> the <var>iterable</var> passed is empty:</p> + +<pre class="brush: js">var p = Promise.all([]); // will be immediately resolved +var p2 = Promise.all([1337, "hi"]); // non-promise values will be ignored, but the evaluation will be done asynchronously +console.log(p); +console.log(p2) +setTimeout(function() { + console.log('the stack is now empty'); + console.log(p2); +}); + +// logs +// Promise { <state>: "fulfilled", <value>: Array[0] } +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: Array[2] } +</pre> + +<h3 id="Promise.all_fail-fast_behaviour"><code>Promise.all</code> fail-fast behaviour</h3> + +<p><code>Promise.all</code> is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then <code>Promise.all</code> will reject immediately.</p> + +<pre class="brush: js">var p1 = new Promise((resolve, reject) => { + setTimeout(() => resolve('one'), 1000); +}); +var p2 = new Promise((resolve, reject) => { + setTimeout(() => resolve('two'), 2000); +}); +var p3 = new Promise((resolve, reject) => { + setTimeout(() => resolve('three'), 3000); +}); +var p4 = new Promise((resolve, reject) => { + setTimeout(() => resolve('four'), 4000); +}); +var p5 = new Promise((resolve, reject) => { + reject(new Error('reject')); +}); + + +// Using .catch: +Promise.all([p1, p2, p3, p4, p5]) +.then(values => { + console.log(values); +}) +.catch(error => { + console.log(error.message) +}); + +//From console: +//"reject" + +</pre> + +<p>It is possible to change this behaviour by handling possible rejections:</p> + +<pre class="brush: js">var p1 = new Promise((resolve, reject) => { + setTimeout(() => resolve('p1_delayed_resolvement'), 1000); +}); + +var p2 = new Promise((resolve, reject) => { + reject(new Error('p2_immediate_rejection')); +}); + +Promise.all([ + p1.catch(error => { return error }), + p2.catch(error => { return error }), +]).then(values => { + console.log(values[0]) // "p1_delayed_resolvement" + console.log(values[1]) // "Error: p2_immediate_rejection" +}) +</pre> + +<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('ES2015', '#sec-promise.all', 'Promise.all')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise.all")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.race()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/promise/catch/index.html b/files/tr/web/javascript/reference/global_objects/promise/catch/index.html new file mode 100644 index 0000000000..3360f87fbb --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,201 @@ +--- +title: Promise.prototype.catch() +slug: Web/JavaScript/Reference/Global_Objects/Promise/catch +tags: + - JavaScript + - Promise + - Prototype + - fonksiyon + - metod +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch +--- +<div>{{JSRef}}</div> + +<p>The <strong>catch()</strong> method returns a <code>Promise</code> and deals with rejected cases only. It behaves the same as calling {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}} (in fact, calling <code>obj.catch(onRejected)</code> internally calls <code>obj.then(undefined, onRejected)</code>). This means, that you have to provide <code>onRejected</code> function even if you want to fallback to <code>undefined</code> result value - for example <code>obj.catch(() => {})</code>.</p> + +<div>{{EmbedInteractiveExample("pages/js/promise-catch.html")}}</div> + + + +<p class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox"><var>p.catch(onRejected)</var>; + +p.catch(function(reason) { + // rejection +}); +</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt>onRejected</dt> + <dd>A {{jsxref("Function")}} called when the <code>Promise</code> is rejected. This function has one argument: + <dl> + <dt><code>reason</code></dt> + <dd>The rejection reason.</dd> + </dl> + The Promise returned by <code>catch()</code> is rejected if <code>onRejected</code> throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.</dd> +</dl> + +<h3 id="Dönen_değer">Dönen değer</h3> + +<p>Internally calls <code>Promise.prototype.then</code> on the object upon which is called, passing the parameters <code>undefined</code> and the <code>onRejected</code> handler received; then returns the value of that call (which is a {{jsxref("Promise")}}).</p> + +<div class="warning"> +<p>Note the examples below are throwing instances of <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">Error</a>. This is considered good practice in contrast to throwing Strings: Otherwise the part doing the catching would have to make checks to see if the argument was a string or an error, and you might lose valuable information like stack traces.</p> +</div> + +<p><strong>Demonstration of the internal call:</strong></p> + +<pre class="brush: js">// overriding original Promise.prototype.then/catch just to add some logs +(function(Promise){ + var originalThen = Promise.prototype.then; + var originalCatch = Promise.prototype.catch; + + Promise.prototype.then = function(){ + console.log('> > > > > > called .then on %o with arguments: %o', this, arguments); + return originalThen.apply(this, arguments); + }; + Promise.prototype.catch = function(){ + console.log('> > > > > > called .catch on %o with arguments: %o', this, arguments); + return originalCatch.apply(this, arguments); + }; + +})(this.Promise); + + + +// calling catch on an already resolved promise +Promise.resolve().catch(function XXX(){}); + +// logs: +// > > > > > > called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] +// > > > > > > called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] +</pre> + +<h2 id="Açıklama">Açıklama</h2> + +<p>The <code>catch</code> method can be useful for error handling in your promise composition.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Using_and_chaining_the_catch_method">Using and chaining the <code>catch</code> method</h3> + +<pre class="brush: js">var p1 = new Promise(function(resolve, reject) { + resolve('Success'); +}); + +p1.then(function(value) { + console.log(value); // "Success!" + throw new Error('oh, no!'); +}).catch(function(e) { + console.log(e.message); // "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="Gotchas_when_throwing_errors">Gotchas when throwing errors</h3> + +<pre class="brush: js">// Throwing an error will call the catch method most of the time +var p1 = new Promise(function(resolve, reject) { + throw new Error('Uh-oh!'); +}); + +p1.catch(function(e) { + console.log(e); // "Uh-oh!" +}); + +// Errors thrown inside asynchronous functions will act like uncaught errors +var p2 = new Promise(function(resolve, reject) { + setTimeout(function() { + throw new Error('Uncaught Exception!'); + }, 1000); +}); + +p2.catch(function(e) { + console.log(e); // This is never called +}); + +// Errors thrown after resolve is called will be silenced +var p3 = new Promise(function(resolve, reject) { + resolve(); + throw new Error('Silenced Exception!'); +}); + +p3.catch(function(e) { + console.log(e); // This is never called +});</pre> + +<h3 id="If_it_is_resolved">If it is resolved</h3> + +<pre class="brush: js">//Create a promise which would not call onReject +var p1 = Promise.resolve("calling next"); + +var p2 = p1.catch(function (reason) { + //This is never called + console.log("catch p1!"); + console.log(reason); +}); + +p2.then(function (value) { + console.log("next promise's onFulfilled"); /* next promise's onFulfilled */ + console.log(value); /* calling next */ +}, function (reason) { + console.log("next promise's onRejected"); + console.log(reason); +});</pre> + +<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('ES2015', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td> + <td>{{Spec2('ES2015')}}</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="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise.catch")}}</p> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.then()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/promise/index.html b/files/tr/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..90f9dcabc0 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,317 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - JavaScript + - Promise + - Referans +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +<div>{{JSRef}}</div> + +<div><code><strong>Promise</strong></code> nesnesi eşzamansız olan ve ertelenen işlemlerde kullanılır. Bir <code><strong>Promise</strong></code> nesnesi henüz işlemin tamamlamadığını ama sonradan tamamlanabileceğini gösterir.</div> + +<div></div> + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox">new Promise(function(resolve, reject) { ... });</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt>executor</dt> + <dd><code>resolve </code>ve <code>reject </code>içeren iki parametreli bir fonksiyon nesnesidir. İlk parametre promise nesnesi tamamlandığında, ikinci parametre ise reddettiğinde çağrılır. Bu fonksiyonları işlemimiz bittiğinde (başarılı yada başarısız) çağırırız.</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Oluşturulan bir <code>promise </code>başka bir <code>promise </code>için proxy görevi görür.<br> + Başarılı yada başarısız bir şekilde sonuç üreten asenkron işlemlerin ilişkilendirilmesine olanak tanır.Bu asenkron methodların senkron methodlar gibi sonuç döndürmesi'ni sağlar.Asenkron method hemen sonuçlanmaz.Bunun yerine işlemin tamamlandığı noktayı temsil eden bir <code>promise </code>döndürür.</p> + +<p>Bir <code>Promise</code> şu durumları içerir:</p> + +<ul> + <li><em>pending</em>: ne işlem görmüş ne de red edilmiş başlangıç durumu.</li> + <li><em>fulfilled</em>: operasyon ' un başarılı bir şekilde tamamlandığı durum.</li> + <li><em>rejected</em>: operasyon ' un başarısızlıkla tamamlandığı durum.</li> +</ul> + +<p>Bekleyen bir Promise, bir sonuç döndürerek tamamlanabilir veya bir nedenle reddedilebilir(hata).Bunlardan herhanbiri gerçekleştiğinde (resolve/reject) sıraya konulmuş ilişkili methodlar sıra ile çağrılır.(Promise tamamlandığında yada red edildiğinde sırada bağlanmış bir method var ise o method çalıştırılır.Böylece asenkron işlemler arasında bir rekabet/mücadele olmaz.Sırası gelen çalışır.)</p> + +<p>As the <code>{{jsxref("Promise.then", "Promise.prototype.then()")}}</code> and <code>{{jsxref("Promise.catch", "Promise.prototype.catch()")}}</code> methods return promises, bunlar zincirlenebilirler—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="Özellikler">Özellikler</h2> + +<dl> + <dt><code>Promise.length</code></dt> + <dd>Değeri 1 olan Length özelliği (constructor argümanları sayısı).</dd> + <dt>{{jsxref("Promise.prototype")}}</dt> + <dd>Represents the prototype for the <code>Promise</code> constructor.</dd> +</dl> + +<h2 id="Metodlar">Metodlar</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>Belirtilen bir nedenden dolayı reddedilen <code>Promise</code> nesnesini döndürür.</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="Özellikler_2">Özellikler</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}</p> + +<h3 id="Metodlar_2">Metodlar</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Promise_Oluşturma">Promise Oluşturma</h3> + +<pre class="brush: html hidden"><button id="btn">Promise yap!</button> +<div id="log"></div> +</pre> + +<p>Bu küçük örnek <code>Promise</code> mekanizmasını gösterir. {{HTMLElement("button")}} her tıklandığında <code>testPromise()</code> metodu çağrılır . It creates a promise that will resolve, using {{domxref("window.setTimeout()")}}, to the string "result" 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 the string 'result' (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>Bu örnek buton'a tıkladığınızda çalışır. <code>Promise</code> destekleyen bir tarayıcıya ihtiyacınız var. Buton'a birden fazla tıklamanız durumunda farklı promise nesnelerinin kısa sürede tamamlandığını göreceksiniz.</p> + +<p>{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}</p> + +<h2 id="new_XMLHttpRequest_Kullanım_Örneği">new XMLHttpRequest() Kullanım Örneği</h2> + +<h3 id="Promise_Oluşturma_2">Promise Oluşturma</h3> + +<p>Bu örnekte {{domxref("XMLHttpRequest")}} nesnesinin başarılı yada başarısız durumunu <code>Promise</code> kullanarak nasıl raporlanabildiğini göstermektedir.</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="XHR_ile_görsel_yükleme">XHR ile görsel yükleme</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">Durum</th> + <th scope="col">Yorum</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="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + + + +<div> + + +<p>{{Compat("javascript.builtins.Promise")}}</p> +</div> + + + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</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> |