await tümceleri
for await...of döngüsü ile asenkron iterable'ları gezmeyi öğrenirsin.
for await...of döngüsü
Bazen bir liste promise üretir; her birini sırayla beklemek istersin. for await...of döngüsü, asenkron iterable'ları gezer ve her öğe için await yapar.
async function processUrls(urls) {
for await (const url of fetchEach(urls)) {
console.log(url);
}
}Bu döngü yalnızca bir async fonksiyonun içinde çalışır. Her yinelemede bir sonraki promise çözümlenir; bu yüzden öğeler sırayla işlenir.
Asenkron iterable nedir?
Bir nesne Symbol.asyncIterator metoduna sahipse asenkron iterable'dır. Bu metod bir next() fonksiyonu döndürür; her next() çağrısı bir promise verir. for await...of bu yapıyı otomatik çağırır.
const stream = {
async *[Symbol.asyncIterator]() {
yield 'a'; yield 'b';
}
};
for await (const x of stream) { /* ... */ }Asenkron jeneratörler (async function*) en sık kullanılan asenkron iterable kaynağıdır.
Uygulama Asenkron döngü yaz
async function processUrls(urls) yaz. İçinde for await (const url of fetchEach(urls)) ile her url'i gezip console.log(url) yazdır.
Örnek çözümü göster
async function processUrls(urls) {
for await (const url of fetchEach(urls)) {
console.log(url);
}
}
Kendini test et
-
for await...of ne zaman kullanılır?
- Bir nesnenin özelliklerini gezmek için
- Bir dizi promise'i paralel beklemek için
- Bir promise'i reddetmek için
- Bir dizi promise'i sırayla beklemek için
Cevabı göster
Bir dizi promise'i sırayla beklemek için — Doğru! for await...of asenkron iterable'ları sırayla gezer.
-
for await döngüsünü tamamla
async function processUrls(urls) { ____ (const url of fetchEach(urls)) { console.log(url); } }Cevabı göster
async function processUrls(urls) { for await (const url of fetchEach(urls)) { console.log(url); } } -
for await...of kavramlarını eşleştir
- for await (const x of s)
- async iterable'ı gezer
- Symbol.asyncIterator
- asenkron iterator sembolü
- async function*
- asenkron jeneratör tanımlar
- yield value
- asenkron olarak değer üretir