
Bir önceki makalede Promise'larla nasıl çalışacağımızı öğrendik - .then(), .catch() ve zincirleme. Ancak o Promise'lar hep hazır fonksiyonlardan geliyordu. Peki ya kendi Promise'larımızı yazmak istersek? Bu makalede Promise'ın iç yapısını anlayacak ve sıfırdan Promise oluşturmayı öğreneceğiz.
Promise Oluşturma Sözdizimi
const benimPromise = new Promise(function(resolve, reject) {
// Asenkron işlem burada yapılır
// Başarılı olursa: resolve(değer)
// Başarısız olursa: reject(hata)
});Parametreler
| Parametre | Açıklama |
|---|---|
resolve | Promise'ı başarıyla tamamlamak için çağrılan fonksiyon |
reject | Promise'ı reddetmek (hata) için çağrılan fonksiyon |
Basit Örnekler
Hemen Çözümlenen Promise
const basariliPromise = new Promise((resolve, reject) => {
resolve("İşlem başarılı!");
});
basariliPromise.then(sonuc => {
console.log(sonuc); // "İşlem başarılı!"
});Hemen Reddedilen Promise
const basarisizPromise = new Promise((resolve, reject) => {
reject("Bir hata oluştu!");
});
basarisizPromise.catch(hata => {
console.log(hata); // "Bir hata oluştu!"
});Bekleyen Promise
const bekleyenPromise = new Promise((resolve, reject) => {
// resolve veya reject çağrılmadığı sürece "pending" durumunda kalır
});
console.log(bekleyenPromise); // Promise {<pending>}Gerçek Hayat Örneği: Gecikmeli İşlem
function bekle(saniye) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(`${saniye} saniye beklendi`);
}, saniye * 1000);
});
}
// Kullanımı
bekle(2).then(mesaj => {
console.log(mesaj); // "2 saniye beklendi"
});Gerçek Hayat Örneği: Rastgele Başarı/Başarısızlık
function zaratAt() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const sayi = Math.floor(Math.random() * 6) + 1;
if (sayi === 6) {
resolve("🎉 Altı geldi! Kazandınız!");
} else {
reject(`😢 ${sayi} geldi. Tekrar deneyin.`);
}
}, 1000);
});
}
// Kullanımı
zaratAt()
.then(sonuc => console.log(sonuc))
.catch(hata => console.log(hata));Gerçek Hayat Örneği: Dosya Okuma Simülasyonu
function dosyaOku(dosyaAdi) {
return new Promise((resolve, reject) => {
console.log(`📂 ${dosyaAdi} okunuyor...`);
setTimeout(() => {
// Bazı dosyalar "var", bazıları "yok"
const mevcutDosyalar = ['config.json', 'data.txt', 'users.csv'];
if (mevcutDosyalar.includes(dosyaAdi)) {
resolve({
dosya: dosyaAdi,
icerik: `Bu ${dosyaAdi} dosyasının içeriğidir.`,
boyut: Math.floor(Math.random() * 1000) + ' KB'
});
} else {
reject(`Hata: ${dosyaAdi} bulunamadı!`);
}
}, 1500);
});
}
// Kullanımı
dosyaOku('config.json')
.then(veri => {
console.log("✅ Dosya okundu:");
console.log(" İçerik:", veri.icerik);
console.log(" Boyut:", veri.boyut);
})
.catch(hata => {
console.log("❌", hata);
});
dosyaOku('olmayan.txt')
.then(veri => console.log(veri))
.catch(hata => console.log("❌", hata));Gerçek Hayat Örneği: Renk Animasyonu (Promise ile)
Callback Hell makalesindeki örneği Promise ile yeniden yazalım:
function renkDegistir(yeniRenk, gecikme) {
return new Promise((resolve) => {
setTimeout(() => {
document.body.style.backgroundColor = yeniRenk;
console.log(`🎨 Renk değişti: ${yeniRenk}`);
resolve(); // Değer döndürmeye gerek yok
}, gecikme);
});
}
// Kullanımı - zincirlenebilir!
renkDegistir('crimson', 1000)
.then(() => renkDegistir('coral', 1000))
.then(() => renkDegistir('gold', 1000))
.then(() => renkDegistir('mediumseagreen', 1000))
.then(() => renkDegistir('dodgerblue', 1000))
.then(() => renkDegistir('rebeccapurple', 1000))
.then(() => console.log("🏁 Animasyon tamamlandı!"));Gerçek Hayat Örneği: HTTP İstek Simülasyonu
function httpIstek(url, metod = 'GET') {
return new Promise((resolve, reject) => {
console.log(`🌐 ${metod} isteği gönderiliyor: ${url}`);
// Gerçek dünyada fetch veya XMLHttpRequest kullanılır
setTimeout(() => {
// %80 başarı şansı
const basarili = Math.random() > 0.2;
if (basarili) {
resolve({
status: 200,
data: {
mesaj: "İşlem başarılı",
url: url,
zaman: new Date().toLocaleTimeString()
}
});
} else {
reject({
status: 500,
hata: "Sunucu hatası",
url: url
});
}
}, 1000 + Math.random() * 1000); // 1-2 saniye arası
});
}
// Kullanımı
httpIstek('/api/kullanicilar', 'GET')
.then(yanit => {
console.log("✅ Başarılı:", yanit.status);
console.log(" Veri:", yanit.data);
})
.catch(hata => {
console.log("❌ Hata:", hata.status);
console.log(" Mesaj:", hata.hata);
});resolve() ve reject() ile Değer Geçirme
Promise çözümlendiğinde veya reddedildiğinde değer geçirebiliriz:
function kullaniciDogrula(kullaniciAdi, sifre) {
return new Promise((resolve, reject) => {
setTimeout(() => {
// Basit doğrulama
if (kullaniciAdi === "admin" && sifre === "1234") {
resolve({
basarili: true,
kullanici: {
id: 1,
isim: "Admin Kullanıcı",
rol: "admin"
},
token: "abc123xyz"
});
} else if (!kullaniciAdi || !sifre) {
reject({
kod: "EKSIK_BILGI",
mesaj: "Kullanıcı adı ve şifre gerekli"
});
} else {
reject({
kod: "YANLIS_BILGI",
mesaj: "Kullanıcı adı veya şifre hatalı"
});
}
}, 1000);
});
}
// Kullanımı
kullaniciDogrula("admin", "1234")
.then(sonuc => {
console.log("✅ Giriş başarılı!");
console.log(" Hoşgeldin:", sonuc.kullanici.isim);
console.log(" Token:", sonuc.token);
})
.catch(hata => {
console.log("❌ Giriş başarısız!");
console.log(" Kod:", hata.kod);
console.log(" Mesaj:", hata.mesaj);
});Promise Zincirleme ile CRUD İşlemleri
function veritabaninaBaglan() {
return new Promise(resolve => {
setTimeout(() => {
console.log("📊 Veritabanına bağlanıldı");
resolve({ baglanti: true });
}, 500);
});
}
function kullaniciOlustur(isim) {
return new Promise(resolve => {
setTimeout(() => {
const yeniKullanici = { id: Date.now(), isim: isim };
console.log("👤 Kullanıcı oluşturuldu:", yeniKullanici);
resolve(yeniKullanici);
}, 500);
});
}
function profilOlustur(kullaniciId) {
return new Promise(resolve => {
setTimeout(() => {
const profil = { kullaniciId: kullaniciId, bio: "", avatar: null };
console.log("📝 Profil oluşturuldu");
resolve(profil);
}, 500);
});
}
function hosgeldinEmailiGonder(kullaniciId) {
return new Promise(resolve => {
setTimeout(() => {
console.log("📧 Hoşgeldin emaili gönderildi");
resolve({ gonderildi: true });
}, 500);
});
}
// Hepsini zincirle
veritabaninaBaglan()
.then(() => kullaniciOlustur("Mehmet"))
.then(kullanici => {
return profilOlustur(kullanici.id)
.then(() => kullanici); // Kullanıcıyı bir sonraki adıma geçir
})
.then(kullanici => hosgeldinEmailiGonder(kullanici.id))
.then(() => {
console.log("🎉 Kayıt işlemi tamamlandı!");
})
.catch(hata => {
console.log("❌ Kayıt sırasında hata:", hata);
});Ne Zaman Kendi Promise'ımızı Yazmalıyız?
✅ Yazmalıyız:
- Callback tabanlı eski kodu modernize ederken
- setTimeout/setInterval kullanırken
- Kendi asenkron mantığımızı yazarken
❌ Yazmamıza gerek yok:
fetch()zaten Promise döndürür- Modern kütüphaneler genelde Promise kullanır
async/awaitkullandığımızda (genellikle)
Özet
Bu makalede öğrendiklerimiz:
✅ new Promise((resolve, reject) => {...}) ile Promise oluştururuz
✅ resolve(değer) Promise'ı başarıyla tamamlar
✅ reject(hata) Promise'ı reddeder
✅ setTimeout gibi callback tabanlı kodları Promise'a çevirebiliriz
✅ Promise zincirleme ile karmaşık iş akışları oluştururuz
Bir sonraki makalede async anahtar kelimesini ve Promise'ları daha da kolay kullanmayı öğreneceğiz.


