This translation is incomplete. Please help translate this article from English
Promise nesnesi eşzamansız olan ve ertelenen işlemlerde kullanılır. Bir Promise nesnesi henüz işlemin tamamlamadığını ama sonradan tamamlanabileceğini gösterir.Sözdizimi
new Promise(function(resolve, reject) { ... });
Parametreler
- executor
resolveverejectiç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.
Açıklama
Oluşturulan bir promise başka bir promise için proxy görevi görür.
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 promise döndürür.
Bir Promise şu durumları içerir:
- pending: ne işlem görmüş ne de red edilmiş başlangıç durumu.
- fulfilled: operasyon ' un başarılı bir şekilde tamamlandığı durum.
- rejected: operasyon ' un başarısızlıkla tamamlandığı durum.
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.)
As the and Promise.prototype.then() methods return promises, bunlar zincirlenebilirler—an operation called composition.Promise.prototype.catch()

Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises — this means that the promise is settled, or it is locked into a promise chain. Domenic Denicola's States and fates contains more details about promise terminology.
Özellikler
Promise.length- Değeri 1 olan Length özelliği (constructor argümanları sayısı).
Promise.prototype- Represents the prototype for the
Promiseconstructor.
Metodlar
Promise.all(iterable)- 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.
Promise.race(iterable)- 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.
Promise.reject(reason)- Belirtilen bir nedenden dolayı reddedilen
Promisenesnesini döndürür.
Promise.resolve(value)- Returns a
Promiseobject that is resolved with the given value. If the value is a thenable (i.e. has athenmethod), 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 -Promise.resolve(value)it instead and work with the return value as a promise.
Promise prototype
Özellikler
Metodlar
Örnekler
Promise Oluşturma
Bu küçük örnek Promise mekanizmasını gösterir. <button> her tıklandığında testPromise() metodu çağrılır . It creates a promise that will resolve, using window.setTimeout(), to the string "result" every 1-3 seconds, at random. The Promise() constructor is used to create the promise.
The fulfillment of the promise is simply logged, via a fulfill callback set using p1.then(). A few logs shows how the synchronous part of the method is decoupled of the asynchronous completion of the promise.
'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/>');
}
Bu örnek buton'a tıkladığınızda çalışır. Promise 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.
new XMLHttpRequest() Kullanım Örneği
Promise Oluşturma
Bu örnekte XMLHttpRequest nesnesinin başarılı yada başarısız durumunu Promise kullanarak nasıl raporlanabildiğini göstermektedir.
'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);
XHR ile görsel yükleme
Another simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub promise-test repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely.
Specifications
| Specification | Durum | Yorum |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Promise' in that specification. |
Standard | Initial definition in an ECMA standard. |
| ECMAScript (ECMA-262) The definition of 'Promise' in that specification. |
Living Standard |
Tarayıcı uyumluluğu
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Promise | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
Promise() constructor | Chrome Full support 32 | Edge Full support 12 | Firefox
Full support
29
| IE No support No | Opera Full support 19 | Safari
Full support
8
| WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android
Full support
29
| Opera Android Full support 19 | Safari iOS
Full support
8
| Samsung Internet Android Full support 2.0 | nodejs
Full support
0.12
|
all() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
allSettled() | Chrome Full support 76 | Edge Full support 79 | Firefox Full support 71 | IE No support No | Opera Full support 63 | Safari Full support 13 | WebView Android Full support 76 | Chrome Android Full support 76 | Firefox Android No support No | Opera Android Full support 54 | Safari iOS Full support 13 | Samsung Internet Android No support No | nodejs Full support 12.9.0 |
catch() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
finally() | Chrome Full support 63 | Edge Full support 18 | Firefox Full support 58 | IE No support No | Opera Full support 50 | Safari Full support 11.1 | WebView Android Full support 63 | Chrome Android Full support 63 | Firefox Android Full support 58 | Opera Android Full support 46 | Safari iOS Full support 11.3 | Samsung Internet Android Full support 8.0 | nodejs Full support 10.0.0 |
race() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
reject() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
resolve() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
then() | Chrome Full support 32 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 19 | Safari Full support 8 | WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android Full support 29 | Opera Android Full support 19 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
Legend
- Full support
- Full support
- No support
- No support
- See implementation notes.
- See implementation notes.
Ayrıca bakınız
- Promises/A+ specification
- Jake Archibald: JavaScript Promises: There and Back Again
- Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript
- Matt Greer: JavaScript Promises ... In Wicked Detail
- Forbes Lindesay: promisejs.org
- Nolan Lawson: We have a problem with promises — Common mistakes with promises
- Promise polyfill