diff --git a/1-js/11-async/05-promise-api/article.md b/1-js/11-async/05-promise-api/article.md index ed071910c..23f7a9980 100644 --- a/1-js/11-async/05-promise-api/article.md +++ b/1-js/11-async/05-promise-api/article.md @@ -1,26 +1,25 @@ # Promise API -There are 5 static methods in the `Promise` class. We'll quickly cover their use cases here. +`Promise`de 5 statik yöntem vardır. Kullanım davalarını burada hızlı bir şekilde ele alacağız. ## Promise.resolve -The syntax: +Söz dizimi: ```js let promise = Promise.resolve(value); ``` -Returns a resolved promise with the given `value`. - -Same as: +Verilen `value` ile çözülmüş olan bir söz verir. +Buradaki gibi: ```js let promise = new Promise(resolve => resolve(value)); ``` -The method is used when we already have a value, but would like to have it "wrapped" into a promise. +Yöntem zaten bir değere sahipken kullanılır. Ancal bir söz içine "sarılmış" olmasını ister. -For instance, the `loadCached` function below fetches the `url` and remembers the result, so that future calls on the same URL return it immediately: +Örneğin, `loadCached` fonksiyonu aşağıda `url`yi alır ve sonucu hatırlar. Böylece aynı URL'deki gelecekteki çağrılar hemen döndürülür. ```js function loadCached(url) { @@ -41,59 +40,60 @@ function loadCached(url) { } ``` -We can use `loadCached(url).then(…)`, because the function is guaranteed to return a promise. That's the purpose `Promise.resolve` serves in the line `(*)`: it makes sure the interface is unified. We can always use `.then` after `loadCached`. +`loadCached(url).then(…)` kullanabiliriz. Çünkü fonksiyonun bir söz döndürmesi garantilidir. Amaç `Promise.resolve` `(*)` doğrultusunda hizmet eder: Arayüzünün birleşik olduğundan emin olun. `.then`den sonra her zaman `loadCached` kullanabiliriz. ## Promise.reject -The syntax: +Söz dizimi: ```js let promise = Promise.reject(error); ``` -Create a rejected promise with the `error`. +`error` ile reddedilen bir söz oluşturun. -Same as: +Yukarıdaki ile aynı: ```js let promise = new Promise((resolve, reject) => reject(error)); ``` -We cover it here for completeness, rarely used in real code. +Gerçek kodda nadiren kullanılan, bütünlük için buradayız. ## Promise.all -Let's say we want to run many promises to execute in parallel, and wait till all of them are ready. +Paralel olarak yürütülmek için birçok söz vermek isteriz ve hepsinin hazır olmasını bekleriz. -For instance, download several URLs in parallel and process the content when all are done. +Örneğin, paralel olarak birkaç URL'yi indirin ve hepsi bittiğinde içeriği işleyin. -That's what `Promise.all` is for. +Bunun için `Promise.all`. -The syntax is: +Söz dizimi: ```js let promise = Promise.all([...promises...]); ``` -It takes an array of promises (technically can be any iterable, but usually an array) and returns a new promise. +Yeni bir söz alır ve bir dizi söz alır (technically can be any iterable, but usually an array.) -The new promise resolves when all listed promises are settled and has an array of their results. +Yeni söz, listelenen tüm sözlerin yerine getirildiği ve sonuçların bir dizisine sahip olduğunda karar verir. -For instance, the `Promise.all` below settles after 3 seconds, and then its result is an array `[1, 2, 3]`: +Örneğin, aşağıdaki `Promise.all` 3 saniye sonra yerleşir ve sonucu `[1, 2, 3]` dizisidir: ```js run Promise.all([ new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1 new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2 new Promise(resolve => setTimeout(() => resolve(3), 1000)) // 3 -]).then(alert); // 1,2,3 when promises are ready: each promise contributes an array member +]).then(alert); // 1,2,3 sözler hazır olduğunda: her söz bir dizi üyesine katkıda bulunur ``` -Please note that the relative order is the same. Even though the first promise takes the longest time to resolve, it is still first in the array of results. +Lütfen göreli siparişin aynı olduğunu unutmayın. İlk sözün sözülmesi uzun sürse bile sonuçta ilk sırada yer almaktadır. + +Yayın bir hile, bir dizi iş verisini bir dizi sözle eşleştirmek ve ardından bunu `Promise.all` içine kaydırmaktır. -A common trick is to map an array of job data into an array of promises, and then wrap that into `Promise.all`. +Örneğin, eğer bir dizi URL'miz varsa hepsini şöyle getirebiliriz: -For instance, if we have an array of URLs, we can fetch them all like this: ```js run let urls = [ @@ -102,17 +102,18 @@ let urls = [ 'https://api.github.com/users/jeresig' ]; -// map every url to the promise of the fetch +// Her URL'yi getirme sözüyle eşleyin let requests = urls.map(url => fetch(url)); -// Promise.all waits until all jobs are resolved +// Tüm işler çözülene kadar Promise.all bekler Promise.all(requests) .then(responses => responses.forEach( response => alert(`${response.url}: ${response.status}`) )); ``` -A bigger example with fetching user information for an array of github users by their names (or we could fetch an array of goods by their ids, the logic is same): +Bir dizi github kullanıcısı için kullanıcı bilgilerini adlarına göre almakla ilgili daha büyük bir örnek (veya bir mal dizisini kimlikleriyle alabiliriz. Mantık aynıdır): + ```js run let names = ['iliakan', 'remy', 'jeresig']; @@ -121,22 +122,22 @@ let requests = names.map(name => fetch(`https://api.github.com/users/${name}`)); Promise.all(requests) .then(responses => { - // all responses are ready, we can show HTTP status codes + // Tüm cevaplar hazır. HTTP durum kodlarını gösterebiliriz for(let response of responses) { - alert(`${response.url}: ${response.status}`); // shows 200 for every url + alert(`${response.url}: ${response.status}`); // Her URL için 200 gösterir } return responses; }) - // map array of responses into array of response.json() to read their content + // Yanıt dizisini, içeriğini okumak için response.json() dizisine eşleyin .then(responses => Promise.all(responses.map(r => r.json()))) - // all JSON answers are parsed: "users" is the array of them + // Tüm JSON cevapları ayrıştırılır: "users" bunların dizisidir. .then(users => users.forEach(user => alert(user.name))); ``` -**If any of the promises is rejected, `Promise.all` immediately rejects with that error.** +**Eğer sözlerden herhangi biri ret edildiyse `Promise.all` bu hatayı hemen ret eder** -For instance: +Örneğin: ```js run Promise.all([ @@ -148,32 +149,34 @@ Promise.all([ ]).catch(alert); // Error: Whoops! ``` -Here the second promise rejects in two seconds. That leads to immediate rejection of `Promise.all`, so `.catch` executes: the rejection error becomes the outcome of the whole `Promise.all`. +İşte ikinci söz iki saniye içinde reddediyor. Bu `Promise.all`un hemen reddedilmesine yol açar, bu yüzden `.catch` çalıştırır: reddedilme hatası tüm `Promise.all`un sonucudur. + ```warn header="In case of an error, other promises are ignored" -If one promise rejects, `Promise.all` immediately rejects, completely forgetting about the other ones in the list. Their results are ignored. +Eğer bir söz reddederse, `Promise.all` derhal reddeder. Listedeki diğerlerini tamamen unutur. Onların sonuçları göz ardı edilir. -For example, if there are multiple `fetch` calls, like in the example above, and one fails, other ones will still continue to execute, but `Promise.all` don't watch them any more. They will probably settle, but the result will be ignored. +Örneğin, yukarıdaki örnekte olduğu gibi birden fazla `fetch` çağrısı varsa ve biri başarısız olursa diğeri hala yürütülmeye devam eder. Ancak `Promise.all` artık onları izlememektedir. Muhtemelen yerleşecekler ancak sonuç göz ardı edilecektir. -`Promise.all` does nothing to cancel them, as there's no concept of "cancellation" in promises. In [another chapter](fetch-abort) we'll cover `AbortController` that aims to help with that, but it's not a part of the Promise API. +`Promise.all` sözlerinde "iptal" kavramı olmadığı için onları iptal edecek hiçbir şey yapmaz. [Başka bir bölümde](fetch-abort) bu konuda yardımcı olmayı amaçlayan `AbortController`ı ele alacağız. Ancak bu Promise API'sinin bir parçası değil. ``` ````smart header="`Promise.all(...)` allows non-promise items in `iterable`" -Normally, `Promise.all(...)` accepts an iterable (in most cases an array) of promises. But if any of those objects is not a promise, it's wrapped in `Promise.resolve`. +Normalde, `Promise.all(...)` sözlerin yenilenebilir (çoğu durumda bir dizi) kabul eder. Ancak bu nesnelerden herhangi biri bir söz değilse `Promise.respove` içine sarılır. +``` -For instance, here the results are `[1, 2, 3]`: +Örneğin burada `[1, 2, 3]` döner: ```js run Promise.all([ new Promise((resolve, reject) => { setTimeout(() => resolve(1), 1000) }), - 2, // treated as Promise.resolve(2) - 3 // treated as Promise.resolve(3) + 2, // Promise.resolve(2) olarak kabul edildi. + 3 // Promise.resolve(3) olarak kabul edildi. ]).then(alert); // 1, 2, 3 ``` -So we are able to pass non-promise values to `Promise.all` where convenient. +Bu yüzden uygun olmayan durumlarda `Promise.all`a söz etmeyen değerleri aktarabiliriz. ```` @@ -181,24 +184,24 @@ So we are able to pass non-promise values to `Promise.all` where convenient. [recent browser="new"] -`Promise.all` rejects as a whole if any promise rejects. That's good in cases, when we need *all* results to go on: +Herhangi bir söz reddederse `Promise.all` bir bütün olarak eder. Devam etmek için *all* sonuçlarına ihtiyacımız olduğunda bu iyidir: ```js Promise.all([ fetch('/template.html'), fetch('/style.css'), fetch('/data.json') -]).then(render); // render method needs them all +]).then(render); // render yöntemi hepsine ihtiyaç duyuyor ``` -`Promise.allSettled` waits for all promises to settle: even if one rejects, it waits for the others. The resulting array has: +`Promise.allSettled` tüm sözlerin yerine getirilmesini bekler: biri reddetse bile diğerini bekler. Sonuçta ortaya çıkan dizin: -- `{status:"fulfilled", value:result}` for successful responses, -- `{status:"rejected", reason:error}` for errors. +- `{status:"fulfilled", value:result}` başarılı cevap için, +- `{status:"rejected", reason:error}` hatalar için. -For example, we'd like to fetch the information about multiple users. Even if one request fails, we're interested in the others. +Örneğin, birden fazla kullanıcı hakkında bilgi edinmek istiyoruz. Bir istek başarısız olsa bile diğerleriyle de ilgileniyoruz -Let's use `Promise.allSettled`: +Hadi `Promise.allSettled` kullanalım: ```js run let urls = [ @@ -220,7 +223,7 @@ Promise.allSettled(urls.map(url => fetch(url))) }); ``` -The `results` in the line `(*)` above will be: +Yukarıdaki satırdaki `results` `(*)` olacak: ```js [ {status: 'fulfilled', value: ...response...}, @@ -229,11 +232,11 @@ The `results` in the line `(*)` above will be: ] ``` -So, for each promise we get its status and `value/reason`. +Dolayısıyla, her söz için onun satütüsünü ve `değer/sebep` bilgisini alırız. ### Polyfill -If the browser doesn't support `Promise.allSettled`, it's easy to polyfill: +Eğer tarayıcı `Promise.allSettled` özelliğini desteklemiyorsa, polyfill kolaydır. ```js if(!Promise.allSettled) { @@ -249,23 +252,23 @@ if(!Promise.allSettled) { } ``` -In this code, `promises.map` takes input values, turns into promises (just in case a non-promise was passed) with `p => Promise.resolve(p)`, and then adds `.then` handler to it. +Bu kodda, `promises.map` giriş değerini alır, `p => Promise.resolve(p)` ile sözleri döndürüyor (sadece bir söz verilmemişse) ve sonra bunu işleyiciye ekler. -That handler turns a successful result `v` into `{state:'fulfilled', value:v}`, and an error `r` into `{state:'rejected', reason:r}`. That's exactly the format of `Promise.allSettled`. +Bu işleyici başarılı bir `v` sonucusunu `{state:'fulfilled', value:v}` ve bir `r` hatasını `{state:'rejected', reason:r}` olarak çevirir. Bu `Promise.allSettled` formatıyla aynıdır. -Then we can use `Promise.allSettled` to get the results or *all* given promises, even if some of them reject. +Sonra bazı sonuçları reddetse bile sonuçları almak ya da *all* sözleri vermek için `Promise.allSettled`i kullanabiliriz. ## Promise.race -Similar to `Promise.all`, it takes an iterable of promises, but instead of waiting for all of them to finish, it waits for the first result (or error), and goes on with it. +`Promise.all` benzer şekilde sözler yenilenebilir. Ancak hepsinin bitmesini beklemek yerine ilk sonucu (veya hatayı) bekler ve devam eder. -The syntax is: +Söz dizimi: ```js let promise = Promise.race(iterable); ``` -For instance, here the result will be `1`: +Mesela burada sonuç `1` olacak: ```js run Promise.race([ @@ -275,18 +278,17 @@ Promise.race([ ]).then(alert); // 1 ``` -So, the first result/error becomes the result of the whole `Promise.race`. After the first settled promise "wins the race", all further results/errors are ignored. - -## Summary +Böylece ilk sonuç/hata bütün `Promise.race` sonucu olur. İlk kararlaştırılan sözün ardından "yarışı kazanır", diğer tüm sonuçlar/hatalar göz ardı edilir -There are 5 static methods of `Promise` class: +## Özetle -1. `Promise.resolve(value)` -- makes a resolved promise with the given value. -2. `Promise.reject(error)` -- makes a rejected promise with the given error. -3. `Promise.all(promises)` -- waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, then it becomes the error of `Promise.all`, and all other results are ignored. -4. `Promise.allSettled(promises)` (a new method) -- waits for all promises to resolve or reject and returns an array of their results as object with: - - `state`: `'fulfilled'` or `'rejected'` - - `value` (if fulfilled) or `reason` (if rejected). -5. `Promise.race(promises)` -- waits for the first promise to settle, and its result/error becomes the outcome. +`Promise` sınıfının 5 statik metodu vardır: -Of these five, `Promise.all/allSettled` are the most common in practice. +1. `Promise.resolve(value)` -- verilen değerle çözümlenmiş bir söz verir. +2. `Promise.reject(error)` -- verilen hata ile reddedilen bir söz verir.. +3. `Promise.all(promises)` -- çözmek için tüm sözleri bekler ve sonuçlarının bir dizisini döndürür. Eğer verilen sözlerden herhangi biri reddederse o zaman `Promise.all` hatası olur ve diğer tüm sonuçlar göz ardı edilir. +4. `Promise.allSettled(promises)` (yeni bir metod) -- tüm sözlerin çözülmesini veya reddedilmesini bekler ve sonuçlarının bir dizisini nesne olarak döndürür. + - `state`: `'fulfilled'` yada `'rejected'` + - `value` (if fulfilled) ya da `reason` (reddedilirse). +5. `Promise.race(promises)` -- ilk yerlmeşmeye söz vermek için bekler ve sonucu/hatası sonuç olur. +Bu beş maddede `Promise.all/allSettled` en yaygın kullanılanıdır.