30 Kasım 2024 • 20 dakikalık okuma
JavaScript Promise, asenkron işlemin durumunu ve işlem sonucunu tutar. Uzun süren asenkron işlemin tamamlandığında işlemin başarılı olup olmadığını ve işlem sonucunu geri döndürür.
ECMAScript 2015 (ES6) spesifikasyonu ile JavaScript diline, Promise özelliği eklenmiştir. JavaScript Promise, asenkron işlemin durumunu ve işlem sonucunu tutan nesnedir. Uzun süren asenkron bir işlem tamamlandığında işlemin başarılı olup olmadığını ve işlem sonucunu geri döndürür. Async/Await altyapısında Promise nesnesi vardır. Promise nesnesinin en önemli özelliği .then() metodu ile arka arkaya çağırılabilirler. fetch() API metodu ve jQuery kütüphanesindeki $.ajax(), $.get(), $.post() metotları ve geriye promise nesnesi döndürür.
Birden fazla sayıda asenkron işlem yapılacaksa ve bu asenkron işlemler bir önceki işlemin sonucunu beklemek zorunda kalındığı durumlarda kullanılırlar. Async ve await komutları ile promise nesnesine göre çok daha sade, okunaklı ve kolay biçimde asenkron işlemler gerçekleştirilebilmektedir. Promise yöntemi, async/await yöntemine göre fazla kod yazımını gerektirir fakat daha detaylı işlemler yapmak ve detaylı hata yakalama gerektiğinde kullanılabilir.
Promise nesnesinin en yaygın kullanımı fetch() metodu ile yapılan isteklerde kullanılabilir. İşlem başarılı ise Promise nesnesinin .then() fonksiyonun ilk parametresi başarılı ise çalıştırılır. Hata meydana gelmiş ise ikinci parametre olarak geçilen fonksiyon çalıştırılır.
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(
function (response) {
// fetch successful get data.
},
function (error) {
// an error occured.
console.log(error);
}
);
Promise nesnesinin en önemli özelliği .then() metodu ile arka arkaya çağırılabilirler. Herhangi bir adımda hata meydana gelir ise .catch() metodu ile hata yakalanabilir.
Örneğin;
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function (response) {
console.log("response", response);
return response.json();
})
.then(function (result) {
console.log("post result", result);
})
.catch(function (error){
// an error occured.
console.log(error);
});
Örneğin, ilk işlemin sonrasında ikinci bir istek yapıldığı durum; ilk istekte ilgili gönderi bilgileri, başarı ile tamamlandığında gönderinin yorumları getiriliyor;
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function (responsePost) {
console.log("responsePost", responsePost);
return responsePost.json();
})
.then(function (resultPost) {
console.log("post result", resultPost);
return fetch('https://jsonplaceholder.typicode.com/comments?postId=' + resultPost.id);
})
.then(function (responseComments){
console.log("responseComments", responseComments);
return responseComments.json();
})
.then(function(resultComments)
{
console.log("comments result", resultComments);
})
.catch(function (error){
// an error occured.
console.log(error);
});
Promise nesnesinin 3 durumu vardır. Bunlar;
Genellikle Promise nesnesi oluşturulmaya ihtiyaç duyulmaz fetch() metodu gibi Promise nesnesi döndüren metotlar kullanılır. İhtiyaç duyulur ise new ile yeni bir Promise nesnesi oluşturulabilir. işlemi fullfiled duruma getirip işlemi tamamlamak için ilk parametre, işlemi rejected duruma getirip hata verdirmek için ikinci parametre çağırılır;
var isOK = true;
var promise = new Promise(function (resolve, reject) {
// Condition to resolve or reject the promise
if(isOK) {
resolve("İşlem tamamlandı!");
}
else {
reject("Hata oluştu.");
}
});
console.log(promise); // Promise {<fulfilled>: 'İşlem tamamlandı!'}
ya da ES6 şeklinde;
const isOK = true;
const promise = new Promise((resolve, reject) => {
// Condition to resolve or reject the promise
if(isOK) {
resolve("İşlem tamamlandı!");
}
else {
reject("Hata oluştu.");
}
});
console.log(promise); // Promise {<fulfilled>: 'İşlem tamamlandı!'}
Başarılı ve hata durumlarını ele alan metotlar yazılıp, .then() fonksiyonunun başarılı olan durum için ilk parametresine, başarısız olan durum için ikinci parametresine geçilir.
function successHandler(result) {
console.log("SUCCESS: ", result);
}
function errorHandler(error) {
console.log("OPPS ERROR: ", error);
}
promise.then(successHandler, errorHandler);
ya da başarılı ve hata durumlarını ele alan metotlar yazılıp, başarılı olan durum için .then() fonksiyonununa, başarısız olan durum .catch() fonksiyonuna parametre olarak geçilir.
function successHandler(result) {
console.log("SUCCESS: ", result);
}
function errorHandler(error) {
console.log("OPPS ERROR: ", error);
}
promise.then(successHandler).catch(errorHandler);
Promise yöntemi, async/await yöntemine göre fazla kod yazımını gerektirir fakat daha detaylı işlemler yapmak ve detaylı hata yakalama gerektiğinde kullanılabilir. Örneğin, Promise yöntemi ile yapılan işlemler;
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function (responsePost) {
return responsePost.json();
})
.then(function (resultPost) {
console.log("post result", resultPost);
return fetch('https://jsonplaceholder.typicode.com/comments?postId=' + resultPost.id);
})
.then(function (responseComments){
return responseComments.json();
})
.then(function(resultComments)
{
console.log("comments result", resultComments);
})
.catch(function (error){
// an error occured.
console.log(error);
});
Aynı işlemin async/await yöntemi ile yapılması; Bu yöntemde await kodu async fonksiyon içine yazılmalıdır.
async function getData()
{
try {
const responsePost = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const resultPost = await responsePost.json();
console.log("post result", resultPost);
const responseComments = await fetch('https://jsonplaceholder.typicode.com/comments?postId=' + resultPost.id);
const resultComments = await responseComments.json();
console.log("comments result", resultComments);
}
catch (error) {
// an error occured.
console.log(error);
}
}
getData();
Promise nesnesindeki metotlar sayesinde birden fazla Promise nesnesi ile işlem yapılabilir;
Birden fazla promise nesnesini parametre olarak alır ve tümü işlemler tamamlanır ise sonuçları döndürür.
const promisePosts = fetch('https://jsonplaceholder.typicode.com/posts');
const promiseUsers = fetch('https://jsonplaceholder.typicode.com/users');
const promisePhotos = fetch('https://jsonplaceholder.typicode.com/photos');
Promise.all([promisePosts, promiseUsers, promisePhotos]).then((results) => {
results.forEach((result) => {
console.log("result", result);
result.json().then((json) => console.log(json));
});
});
Birden fazla promise nesnesini parametre olarak alır ve ilk biten başarılı ya da başarısız işlemin sonucunu döndürür.
const promisePosts = fetch('https://jsonplaceholder.typicode.com/posts');
const promiseUsers = fetch('https://jsonplaceholder.typicode.com/users');
const promisePhotos = fetch('https://jsonplaceholder.typicode.com/photos');
Promise.race([promisePosts, promiseUsers, promisePhotos]).then((result) => {
console.log("result", result);
result.json().then((json) => console.log(json));
});
Birden fazla promise nesnesini parametre olarak alır ve ilk biten başarılı işlemin sonucunu döndürür.
const promisePosts = fetch('https://jsonplaceholder.typicode.com/posts');
const promiseUsers = fetch('https://jsonplaceholder.typicode.com/users');
const promisePhotos = fetch('https://jsonplaceholder.typicode.com/photos');
Promise.any([promisePosts, promiseUsers, promisePhotos]).then((result) => {
console.log("result", result);
result.json().then((json) => console.log(json));
});
Birden fazla promise nesnesini parametre olarak alır ve tüm işlemlerin sonuçlarını döndürür.
const promisePosts = fetch('https://jsonplaceholder.typicode.com/posts');
const promiseUsers = fetch('https://jsonplaceholder.typicode.com/users');
const promisePhotos = fetch('https://jsonplaceholder.typicode.com/photos');
Promise.allSettled([promisePosts, promiseUsers, promisePhotos]).then(console.log);