JavaScript Promise Nedir?

JavaScript JS Promise Async Await Async/Await ES ES6 ES2015 ES2017 Fetch Client Side Programlama Client Side Programming

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.

Promise Nedir?

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.

Promise Ne Zaman Kullanılı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 Nasıl Kullanılır?

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.

Kod

fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(
        function (response) {
            // fetch successful get data.
        },
        function (error) {
            // an error occured.
            console.log(error);
        }
    );

Promise Hata Yakalamak

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;

Kod

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);
    });

Promise Birden Fazla Asenkron İşlem Yapmak

Ö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;

Kod

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 Nesnesi Özellikleri

Promise nesnesinin 3 durumu vardır. Bunlar;

  1. pending : İşlemin devam ettiğini belirtir
  2. fullfiled : İşlem tamamlandı
  3. rejected : Hata oluştu

Promise Nesnesi Nasıl Oluşturulur?

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;

Kod

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;

Kod

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ı!'}

Oluşturulan Promise Nesnesi Nasıl Kullanılır?

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.

Kod

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.

Kod

function successHandler(result) {
    console.log("SUCCESS: ", result);
}

function errorHandler(error) {
    console.log("OPPS ERROR: ", error);
}

promise.then(successHandler).catch(errorHandler);

Promise ve Async/Await Kodu Farkı

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;

Kod

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.

Kod

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();

Birden Fazla Promise İle İşlem Yapmak

Promise nesnesindeki metotlar sayesinde birden fazla Promise nesnesi ile işlem yapılabilir;

  • Promise.all();
  • Promise.race();
  • Promise.any();
  • Promise.allSettled();

Promise.all()

Birden fazla promise nesnesini parametre olarak alır ve tümü işlemler tamamlanır ise sonuçları döndürür.

Kod


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));
    });
    
});

Promise.race()

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.

Kod

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));
        
});

Promise.any()

Birden fazla promise nesnesini parametre olarak alır ve ilk biten başarılı işlemin sonucunu döndürür.

Kod

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));
        
});

Promise.allSettled()

Birden fazla promise nesnesini parametre olarak alır ve tüm işlemlerin sonuçlarını döndürür.

Kod

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);

Kaynaklar

  1. JavaScript Promise Object , w3schools.com, 29.11.2024 tarihinde alındı.
  2. Promise , developer.mozilla.org, 29.11.2024 tarihinde alındı.
  3. JavaScript Versions , w3schools.com, 29.11.2024 tarihinde alındı.
  4. How Promises Work in JavaScript – A Comprehensive Beginner's Guide , freecodecamp.org, 29.11.2024 tarihinde alındı.
  5. Are you bad, good, better or best with Async JS? JS Tutorial: Callbacks, Promises, Generators , LearnCode.academy, YouTube.com, 29.11.2024 tarihinde alındı.
  6. Asynchronous JavaScript – Callbacks, Promises, and Async/Await Explained , freecodecamp.org, 29.11.2024 tarihinde alındı.
  7. JavaScript Promises: an introduction , web.dev, 29.11.2024 tarihinde alındı.
  8. Returning a Javascript Promise from $.ajax call , stackoverflow.com, 30.11.2024 tarihinde alındı.
  9. .promise() , stackoverflow.com, 30.11.2024 tarihinde alındı.
  10. How to pass parameter to a Promise? , stackoverflow.com, 30.11.2024 tarihinde alındı.


Beğen