JavaScript'te Promise Zincirlerinde İstisnalar
Herhangi bir nedenle promise'imizin hata ile sonuçlandığını varsayalım:
let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
reject('error');
}, 3000);
});
Bu durumda kodun yürütülmesi hemen,
içinde hata işleyici fonksiyon bulunan
then'e veya ilk catch'e atlayacaktır,
hangisi önce karşılaşılırsa.
İlk duruma bir örnek:
promise.then(
function(result) {
return result + '1';
}
).then(
function(result) {
return result + '2';
},
function(error) {
// yürütme hemen buraya atlayacak
}
).then(
function(result) {
console.log(result);
}
);
İkinci duruma bir örnek:
promise.then(
function(result) {
return result + '1';
}
).then(
function(result) {
return result + '2';
}
).catch(
function(error) {
// yürütme hemen buraya atlayacak
}
).then(
function(result) {
console.log(result);
}
);
Hata işleyici fonksiyonun iki seçeneği vardır:
Eğer istisnai durumu halledebilirse,
return ile bir sonuç döndürebilir
ve yürütme zincirde devam eder.
Eğer hatayı halledemezse,
ya hiçbir şey döndürmez ya da
throw aracılığıyla bir istisna fırlatabilir.
Bu durumda yürütme, bir sonraki hata yakalayıcısına
(then veya catch - hangisi önce karşılaşılırsa)
atlayacaktır.
Genellikle, zincirdeki tüm hatalar
tek bir yerde yakalanır:
zincirin sonuna bir catch yerleştirilir:
promise.then(
function(result) {
return result + '1';
}
).then(
function(result) {
return result + '2';
}
).catch(
function(error) {
// hata durumunda buraya geleceğiz
}
);
Bu durumda istisna, promise'in kendisinde
oluşabilir veya zincirin herhangi bir halkasında
throw ile fırlatılabilir:
promise.then(
function(result) {
return result + '1';
}
).then(
function(result) {
if (herSeyYolunda) {
return result + '2';
} else {
throw new Error('hata'); // en yakın yakalayıcıya geçiş yap
}
}
)
.then(
function(result) {
return result + '3';
}
).catch(
function(error) {
// en yakın yakalayıcı
}
);
Unutmayın ki, catch özellikle
hatanın teşhisi için gereklidir:
Çözülebilir mi değil mi?
Eğer hata çözülebilirse, catch
çözümü kendisinden sonra gelen then'e iletmelidir.
Eğer çözülemezse (veya bu catch
basitçe nasıl çözüleceğini bilmiyorsa),
ya hiçbir şey döndürmemeliyiz ya da bir istisna fırlatmalıyız:
promise.then(
function(result) {
return result + '1';
}
).then(
function(result) {
return result + '2';
}
).catch(
function(error) {
if (hataCozulebilir) {
return 'veri'; // bir sonraki then'e gönder
} else {
// hiçbir şey döndürme veya istisna fırlat
}
}
).then(
function(result) {
// burada hatayı çöz
}
);