aboutsummaryrefslogtreecommitdiff
path: root/files/tr/web/javascript/reference/global_objects/promise/index.html
blob: 90f9dcabc0b871a1b5043f20decc0e88305c764f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
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">&lt;button id="btn"&gt;Promise yap!&lt;/button&gt;
&lt;div id="log"&gt;&lt;/div&gt;
</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 (&lt;small&gt;Sync code started&lt;/small&gt;)&lt;br/&gt;');

    // 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 (&lt;small&gt;Async code started&lt;/small&gt;)&lt;br/&gt;');
            // 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 (&lt;small&gt;Async code terminated&lt;/small&gt;)&lt;br/&gt;');
        })
    .catch(
        // Log the rejection reason
        function(reason) {
            console.log('Handle rejected promise ('+reason+') here.');
        });

    log.insertAdjacentHTML('beforeend', thisPromiseCount +
        ') Promise made (&lt;small&gt;Sync code terminated&lt;/small&gt;)&lt;br/&gt;');
}</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 &lt;code&gt;Promise&lt;code&gt; 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-&gt; $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 &amp;&amp; (method === 'POST' || method === 'PUT')) {
          uri += '?';
          var argcount = 0;
          for (var key in args) {
            if (args.hasOwnProperty(key)) {
              if (argcount++) {
                uri += '&amp;';
              }
              uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
            }
          }
        }

        client.open(method, uri);
        client.send();

        client.onload = function () {
          if (this.status &gt;= 200 &amp;&amp; this.status &lt; 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-&gt; 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>