diff --git a/1-js/11-async/08-async-await/01-rewrite-async/solution.md b/1-js/11-async/08-async-await/01-rewrite-async/solution.md index 3337ef3c4..1df49180b 100644 --- a/1-js/11-async/08-async-await/01-rewrite-async/solution.md +++ b/1-js/11-async/08-async-await/01-rewrite-async/solution.md @@ -1,33 +1,33 @@ -The notes are below the code: +Poznámky jsou pod kódem: ```js run -async function loadJson(url) { // (1) - let response = await fetch(url); // (2) +async function načtiJson(url) { // (1) + let odpověď = await fetch(url); // (2) - if (response.status == 200) { - let json = await response.json(); // (3) + if (odpověď.status == 200) { + let json = await odpověď.json(); // (3) return json; } - throw new Error(response.status); + throw new Error(odpověď.status); } -loadJson('https://javascript.info/no-such-user.json') - .catch(alert); // Error: 404 (4) +načtiJson('https://javascript.info/takovy-uzivatel-neni.json') + .catch(alert); // Chyba: 404 (4) ``` -Notes: +Poznámky: -1. The function `loadJson` becomes `async`. -2. All `.then` inside are replaced with `await`. -3. We can `return response.json()` instead of awaiting for it, like this: +1. Funkce `načtiJson` se stává asynchronní (`async`). +2. Všechna `.then` uvnitř jsou nahrazena za `await`. +3. Můžeme vrátit `return odpověď.json()` místo čekání na tuto funkci, například: ```js - if (response.status == 200) { - return response.json(); // (3) + if (odpověď.status == 200) { + return odpověď.json(); // (3) } ``` - Then the outer code would have to `await` for that promise to resolve. In our case it doesn't matter. -4. The error thrown from `loadJson` is handled by `.catch`. We can't use `await loadJson(…)` there, because we're not in an `async` function. + Pak by vnější kód musel počkat pomocí `await`, než se tento příslib vyhodnotí. V našem případě na tom nezáleží. +4. Chyba vyvolaná z `načtiJson` je ošetřena pomocí `.catch`. Nemůžeme zde použít `await načtiJson(…)`, protože nejsme uvnitř funkce s `async`. diff --git a/1-js/11-async/08-async-await/01-rewrite-async/task.md b/1-js/11-async/08-async-await/01-rewrite-async/task.md index 0c31737da..416c47c81 100644 --- a/1-js/11-async/08-async-await/01-rewrite-async/task.md +++ b/1-js/11-async/08-async-await/01-rewrite-async/task.md @@ -1,20 +1,20 @@ -# Rewrite using async/await +# Přepište za použití async/await -Rewrite this example code from the chapter using `async/await` instead of `.then/catch`: +Přepište tento příklad kódu z kapitoly za použití `async/await` namísto `.then/catch`: ```js run -function loadJson(url) { +function načtiJson(url) { return fetch(url) - .then(response => { - if (response.status == 200) { - return response.json(); + .then(odpověď => { + if (odpověď.status == 200) { + return odpověď.json(); } else { - throw new Error(response.status); + throw new Error(odpověď.status); } }); } -loadJson('https://javascript.info/no-such-user.json') - .catch(alert); // Error: 404 +načtiJson('https://javascript.info/takovy-uzivatel-neni.json') + .catch(alert); // Chyba: 404 ``` diff --git a/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md b/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md index aa462dbf7..ea9fa66bc 100644 --- a/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md +++ b/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md @@ -1,49 +1,49 @@ -There are no tricks here. Just replace `.catch` with `try..catch` inside `demoGithubUser` and add `async/await` where needed: +Nejsou tady žádné triky. Stačí uvnitř `demoUživatelGitHubu` nahradit `.catch` za `try..catch` a přidat `async/await`, kde jsou zapotřebí: ```js run -class HttpError extends Error { - constructor(response) { - super(`${response.status} for ${response.url}`); - this.name = 'HttpError'; - this.response = response; +class ChybaHttp extends Error { + constructor(odpověď) { + super(`${odpověď.status} pro ${odpověď.url}`); + this.name = 'ChybaHttp'; + this.odpověď = odpověď; } } -async function loadJson(url) { - let response = await fetch(url); - if (response.status == 200) { - return response.json(); +async function načtiJson(url) { + let odpověď = await fetch(url); + if (odpověď.status == 200) { + return odpověď.json(); } else { - throw new HttpError(response); + throw new ChybaHttp(odpověď); } } -// Ask for a user name until github returns a valid user -async function demoGithubUser() { +// Ptáme se na uživatelské jméno, dokud GitHub nevrátí platného uživatele +async function demoUživatelGitHubu() { - let user; + let uživatel; while(true) { - let name = prompt("Enter a name?", "iliakan"); + let jméno = prompt("Zadejte jméno", "iliakan"); try { - user = await loadJson(`https://api.github.com/users/${name}`); - break; // no error, exit loop - } catch(err) { - if (err instanceof HttpError && err.response.status == 404) { - // loop continues after the alert - alert("No such user, please reenter."); + uživatel = await načtiJson(`https://api.github.com/users/${jméno}`); + break; // žádná chyba, opustíme cyklus + } catch(chyba) { + if (chyba instanceof ChybaHttp && chyba.odpověď.status == 404) { + // po alertu bude cyklus pokračovat + alert("Takový uživatel neexistuje, prosím zadejte znovu."); } else { - // unknown error, rethrow - throw err; + // neznámá chyba, vyvoláme ji znovu + throw chyba; } } } - alert(`Full name: ${user.name}.`); - return user; + alert(`Celé jméno: ${uživatel.name}.`); + return uživatel; } -demoGithubUser(); +demoUživatelGitHubu(); ``` diff --git a/1-js/11-async/08-async-await/02-rewrite-async-2/task.md b/1-js/11-async/08-async-await/02-rewrite-async-2/task.md index 13d625d2a..95cfec38a 100644 --- a/1-js/11-async/08-async-await/02-rewrite-async-2/task.md +++ b/1-js/11-async/08-async-await/02-rewrite-async-2/task.md @@ -1,48 +1,48 @@ -# Rewrite "rethrow" with async/await +# Přepište „opětovné vyvolání“ za použití async/await -Below you can find the "rethrow" example. Rewrite it using `async/await` instead of `.then/catch`. +Následuje příklad „opětovného vyvolání“. Přepište jej za použití `async/await` místo `.then/catch`. -And get rid of the recursion in favour of a loop in `demoGithubUser`: with `async/await` that becomes easy to do. +A ve funkci `demoUživatelGitHubu` se zbavte rekurze ve prospěch cyklu: s `async/await` to bude lehké. ```js run -class HttpError extends Error { - constructor(response) { - super(`${response.status} for ${response.url}`); - this.name = 'HttpError'; - this.response = response; +class ChybaHttp extends Error { + constructor(odpověď) { + super(`${odpověď.status} pro ${odpověď.url}`); + this.name = 'ChybaHttp'; + this.odpověď = odpověď; } } -function loadJson(url) { +function načtiJson(url) { return fetch(url) - .then(response => { - if (response.status == 200) { - return response.json(); + .then(odpověď => { + if (odpověď.status == 200) { + return odpověď.json(); } else { - throw new HttpError(response); + throw new ChybaHttp(odpověď); } }); } -// Ask for a user name until github returns a valid user -function demoGithubUser() { - let name = prompt("Enter a name?", "iliakan"); +// Ptáme se na uživatelské jméno, dokud GitHub nevrátí platného uživatele +function demoUživatelGitHubu() { + let jméno = prompt("Zadejte jméno", "iliakan"); - return loadJson(`https://api.github.com/users/${name}`) - .then(user => { - alert(`Full name: ${user.name}.`); - return user; + return načtiJson(`https://api.github.com/users/${jméno}`) + .then(uživatel => { + alert(`Celé jméno: ${uživatel.name}.`); + return uživatel; }) - .catch(err => { - if (err instanceof HttpError && err.response.status == 404) { - alert("No such user, please reenter."); - return demoGithubUser(); + .catch(chyba => { + if (chyba instanceof ChybaHttp && chyba.odpověď.status == 404) { + alert("Takový uživatel neexistuje, prosím zadejte znovu."); + return demoUživatelGitHubu(); } else { - throw err; + throw chyba; } }); } -demoGithubUser(); +demoUživatelGitHubu(); ``` diff --git a/1-js/11-async/08-async-await/03-async-from-regular/solution.md b/1-js/11-async/08-async-await/03-async-from-regular/solution.md index 7e2ab597e..ec9ca9825 100644 --- a/1-js/11-async/08-async-await/03-async-from-regular/solution.md +++ b/1-js/11-async/08-async-await/03-async-from-regular/solution.md @@ -1,18 +1,18 @@ -That's the case when knowing how it works inside is helpful. +Toto je případ, kdy nám pomáhá, že víme, jak to funguje uvnitř. -Just treat `async` call as promise and attach `.then` to it: +Jednoduše zacházejte s voláním `async` jako s příslibem a připojte k němu `.then`: ```js run -async function wait() { +async function čekej() { await new Promise(resolve => setTimeout(resolve, 1000)); return 10; } function f() { - // shows 10 after 1 second + // za 1 sekundu zobrazí 10 *!* - wait().then(result => alert(result)); + čekej().then(výsledek => alert(výsledek)); */!* } diff --git a/1-js/11-async/08-async-await/03-async-from-regular/task.md b/1-js/11-async/08-async-await/03-async-from-regular/task.md index ca7c186ff..5ea74c953 100644 --- a/1-js/11-async/08-async-await/03-async-from-regular/task.md +++ b/1-js/11-async/08-async-await/03-async-from-regular/task.md @@ -1,20 +1,20 @@ -# Call async from non-async +# Volání asynchronní funkce z neasynchronní -We have a "regular" function called `f`. How can you call the `async` function `wait()` and use its result inside of `f`? +Máme „obyčejnou“ funkci nazvanou `f`. Jak můžeme volat `async` funkci `čekej()` a použít její výsledek uvnitř `f`? ```js -async function wait() { +async function čekej() { await new Promise(resolve => setTimeout(resolve, 1000)); return 10; } function f() { - // ...what should you write here? - // we need to call async wait() and wait to get 10 - // remember, we can't use "await" + // ...co byste sem měli napsat? + // musíme volat asynchronní čekej() a čekat, než obdržíme 10 + // pamatujte, že nemůžeme použít „await“ } ``` -P.S. The task is technically very simple, but the question is quite common for developers new to async/await. +P.S. Tento úkol je technicky velmi jednoduchý, ale tato otázka je u vývojářů, kteří s async/await teprve začínají, vcelku běžná. diff --git a/1-js/11-async/08-async-await/article.md b/1-js/11-async/08-async-await/article.md index e679b1c4c..372392d92 100644 --- a/1-js/11-async/08-async-await/article.md +++ b/1-js/11-async/08-async-await/article.md @@ -1,10 +1,10 @@ # Async/await -There's a special syntax to work with promises in a more comfortable fashion, called "async/await". It's surprisingly easy to understand and use. +Existuje speciální syntaxe, která umožňuje pracovat s přísliby pohodlnějším způsobem. Nazývá se „async/await“. Je překvapivě snadné jí porozumět a používat ji. -## Async functions +## Asynchronní funkce -Let's start with the `async` keyword. It can be placed before a function, like this: +Začněme klíčovým slovem `async`. To může být umístěno před funkci, například: ```js async function f() { @@ -12,9 +12,9 @@ async function f() { } ``` -The word "async" before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically. +Slovo „async“ před funkcí znamená jedno jediné: funkce vždy vrátí příslib. Jiné hodnoty budou automaticky zabaleny do splněného příslibu. -For instance, this function returns a resolved promise with the result of `1`; let's test it: +Například tato funkce vrátí splněný příslib s výsledkem `1`; otestujme to: ```js run async function f() { @@ -24,7 +24,7 @@ async function f() { f().then(alert); // 1 ``` -...We could explicitly return a promise, which would be the same: +...Mohli bychom explicitně vrátit příslib, což by bylo totéž: ```js run async function f() { @@ -34,204 +34,204 @@ async function f() { f().then(alert); // 1 ``` -So, `async` ensures that the function returns a promise, and wraps non-promises in it. Simple enough, right? But not only that. There's another keyword, `await`, that works only inside `async` functions, and it's pretty cool. +Klíčové slovo `async` tedy zaručuje, že funkce vrátí příslib, a jiné hodnoty než přísliby do něj zabalí. Jednoduché, že? Ale to není všechno. Existuje další klíčové slovo, `await`, které funguje výhradně uvnitř funkcí s `async` a je opravdu pěkné. ## Await -The syntax: +Syntaxe: ```js -// works only inside async functions -let value = await promise; +// funguje jen v asynchronních funkcích +let hodnota = await příslib; ``` -The keyword `await` makes JavaScript wait until that promise settles and returns its result. +Klíčové slovo `await` přiměje JavaScript počkat, než se příslib usadí, a vrátí jeho výsledek. -Here's an example with a promise that resolves in 1 second: +Následuje příklad s příslibem, který se splní za 1 sekundu: ```js run async function f() { - let promise = new Promise((resolve, reject) => { - setTimeout(() => resolve("done!"), 1000) + let příslib = new Promise((splň, zamítni) => { + setTimeout(() => splň("hotovo!"), 1000) }); *!* - let result = await promise; // wait until the promise resolves (*) + let výsledek = await příslib; // čeká, než se příslib splní (*) */!* - alert(result); // "done!" + alert(výsledek); // "hotovo!" } f(); ``` -The function execution "pauses" at the line `(*)` and resumes when the promise settles, with `result` becoming its result. So the code above shows "done!" in one second. +Výkon funkce se na řádku `(*)` „pozastaví“ a obnoví se až tehdy, když se příslib usadí. Jeho výsledek se uloží do proměnné `výsledek`. Proto uvedený kód zobrazí za jednu sekundu „hotovo!“. -Let's emphasize: `await` literally suspends the function execution until the promise settles, and then resumes it with the promise result. That doesn't cost any CPU resources, because the JavaScript engine can do other jobs in the meantime: execute other scripts, handle events, etc. +Zdůrazněme to: `await` doslova přeruší výkon funkce, dokud se příslib neusadí, a pak jej obnoví s výsledkem příslibu. To nestojí žádné zdroje CPU, protože motor JavaScriptu mezitím může vykonávat jinou práci: spouštět další skripty, ošetřovat události a podobně. -It's just a more elegant syntax of getting the promise result than `promise.then`. And, it's easier to read and write. +Je to jen elegantnější syntaxe získání výsledku příslibu než `příslib.then`. A snadněji se čte a píše. -````warn header="Can't use `await` in regular functions" -If we try to use `await` in a non-async function, there would be a syntax error: +````warn header="V běžných funkcích nelze `await` používat" +Pokud se pokusíme použít `await` v neasynchronní funkci, nastane syntaktická chyba: ```js run function f() { - let promise = Promise.resolve(1); + let příslib = Promise.resolve(1); *!* - let result = await promise; // Syntax error + let výsledek = await příslib; // Syntaktická chyba */!* } ``` -We may get this error if we forget to put `async` before a function. As stated earlier, `await` only works inside an `async` function. +Tuto chybu můžeme získat, když zapomeneme uvést `async` před funkcí. Jak bylo uvedeno, `await` funguje jedině uvnitř funkce s `async`. ```` -Let's take the `showAvatar()` example from the chapter and rewrite it using `async/await`: +Vezměme nyní příklad `zobrazAvatara()` z kapitoly a přepišme jej za použití `async/await`: -1. We'll need to replace `.then` calls with `await`. -2. Also we should make the function `async` for them to work. +1. Musíme nahradit volání `.then` za `await`. +2. Aby to fungovalo, měli bychom také označit funkci jako `async`. ```js run -async function showAvatar() { +async function zobrazAvatara() { - // read our JSON - let response = await fetch('/article/promise-chaining/user.json'); - let user = await response.json(); + // načteme náš JSON + let odpověď = await fetch('/article/promise-chaining/user.json'); + let uživatel = await odpověď.json(); - // read github user - let githubResponse = await fetch(`https://api.github.com/users/${user.name}`); - let githubUser = await githubResponse.json(); + // načteme uživatele GitHubu + let odpověďGitHubu = await fetch(`https://api.github.com/users/${uživatel.name}`); + let uživatelGitHubu = await odpověďGitHubu.json(); - // show the avatar - let img = document.createElement('img'); - img.src = githubUser.avatar_url; - img.className = "promise-avatar-example"; - document.body.append(img); + // zobrazíme avatara + let obrázek = document.createElement('img'); + obrázek.src = uživatelGitHubu.avatar_url; + obrázek.className = "promise-avatar-example"; + document.body.append(obrázek); - // wait 3 seconds - await new Promise((resolve, reject) => setTimeout(resolve, 3000)); + // počkáme 3 sekundy + await new Promise((splň, zamítni) => setTimeout(splň, 3000)); - img.remove(); + obrázek.remove(); - return githubUser; + return uživatelGitHubu; } -showAvatar(); +zobrazAvatara(); ``` -Pretty clean and easy to read, right? Much better than before. +Pěkně čisté a snadno čitelné, že? Mnohem lepší než předtím. -````smart header="Modern browsers allow top-level `await` in modules" -In modern browsers, `await` on top level works just fine, when we're inside a module. We'll cover modules in article . +````smart header="Moderní prohlížeče povolují `await` na nejvyšší úrovni v modulech" +V moderních prohlížečích funguje `await` dobře i na nejvyšší úrovni, když jsme uvnitř modulu. Moduly probereme v článku . -For instance: +Například: ```js run module -// we assume this code runs at top level, inside a module -let response = await fetch('/article/promise-chaining/user.json'); -let user = await response.json(); +// předpokládáme, že tento kód běží na nejvyšší úrovni uvnitř modulu +let odpověď = await fetch('/article/promise-chaining/user.json'); +let uživatel = await odpověď.json(); -console.log(user); +console.log(uživatel); ``` -If we're not using modules, or [older browsers](https://caniuse.com/mdn-javascript_operators_await_top_level) must be supported, there's a universal recipe: wrapping into an anonymous async function. +Jestliže nepoužíváme moduly nebo musíme podporovat i [starší prohlížeče](https://caniuse.com/mdn-javascript_operators_await_top_level), pak existuje univerzální návod: zabalení do anonymní asynchronní funkce. -Like this: +Například: ```js (async () => { - let response = await fetch('/article/promise-chaining/user.json'); - let user = await response.json(); + let odpověď = await fetch('/article/promise-chaining/user.json'); + let uživatel = await odpověď.json(); ... })(); ``` ```` -````smart header="`await` accepts \"thenables\"" -Like `promise.then`, `await` allows us to use thenable objects (those with a callable `then` method). The idea is that a third-party object may not be a promise, but promise-compatible: if it supports `.then`, that's enough to use it with `await`. +````smart header="`await` přijímá „thenable“ objekty" +Stejně jako `příslib.then`, i `await` nám umožňuje používat thenable objekty (ty, které obsahují volatelnou metodu `then`). Myšlenkou je, že objekt třetí strany nemusí být příslib, ale objekt kompatibilní s příslibem: k tomu, abychom jej použili s `await`, stačí, aby podporoval `then`. -Here's a demo `Thenable` class; the `await` below accepts its instances: +Následuje příklad třídy `Thenable`; `await` pod ní přijímá její instance: ```js run class Thenable { - constructor(num) { - this.num = num; + constructor(číslo) { + this.číslo = číslo; } - then(resolve, reject) { - alert(resolve); - // resolve with this.num*2 after 1000ms - setTimeout(() => resolve(this.num * 2), 1000); // (*) + then(splň, zamítni) { + alert(splň); + // splnění s hodnotou this.číslo*2 za 1000 ms + setTimeout(() => splň(this.číslo * 2), 1000); // (*) } } async function f() { - // waits for 1 second, then result becomes 2 - let result = await new Thenable(1); - alert(result); + // počká 1 sekundu, pak výsledek bude 2 + let výsledek = await new Thenable(1); + alert(výsledek); } f(); ``` -If `await` gets a non-promise object with `.then`, it calls that method providing the built-in functions `resolve` and `reject` as arguments (just as it does for a regular `Promise` executor). Then `await` waits until one of them is called (in the example above it happens in the line `(*)`) and then proceeds with the result. +Jestliže `await` obdrží nepříslibový objekt obsahující `.then`, pak tuto metodu zavolá a jako argumenty `splň` a `zamítni` jí poskytne zabudované funkce (tak, jak to učiní pro obvyklý exekutor `Promise`). Pak `await` počká, dokud nebude zavolána jedna z nich (v uvedeném příkladu se to stane na řádku `(*)`), a poté bude pokračovat s výsledkem. ```` -````smart header="Async class methods" -To declare an async class method, just prepend it with `async`: +````smart header="Asynchronní třídní metody" +Chceme-li deklarovat asynchronní třídní metodu, jednoduše před ni uvedeme `async`: ```js run -class Waiter { +class Čekatel { *!* - async wait() { + async čekej() { */!* return await Promise.resolve(1); } } -new Waiter() - .wait() - .then(alert); // 1 (this is the same as (result => alert(result))) +new Čekatel() + .čekej() + .then(alert); // 1 (to je totéž jako (výsledek => alert(výsledek))) ``` -The meaning is the same: it ensures that the returned value is a promise and enables `await`. +Význam je stejný: zajišťuje, že vrácená hodnota je příslib, a umožňuje `await`. ```` -## Error handling +## Ošetřování chyb -If a promise resolves normally, then `await promise` returns the result. But in the case of a rejection, it throws the error, just as if there were a `throw` statement at that line. +Jestliže je příslib normálně splněn, pak `await příslib` vrátí výsledek. V případě zamítnutí však vyvolá chybu, tak, jako by na tomto řádku byl uveden příkaz `throw`. -This code: +Tento kód: ```js async function f() { *!* - await Promise.reject(new Error("Whoops!")); + await Promise.reject(new Error("Ouha!")); */!* } ``` -...is the same as this: +...je stejný jako tento: ```js async function f() { *!* - throw new Error("Whoops!"); + throw new Error("Ouha!"); */!* } ``` -In real situations, the promise may take some time before it rejects. In that case there will be a delay before `await` throws an error. +V reálných situacích může nějakou dobu trvat, než bude příslib zamítnut. V tom případě předtím, než `await` vyvolá chybu, nastane prodleva. -We can catch that error using `try..catch`, the same way as a regular `throw`: +Tuto chybu můžeme zachytit pomocí `try..catch`, stejným způsobem, jako obvyklé `throw`: ```js run async function f() { try { - let response = await fetch('http://no-such-url'); - } catch(err) { + let odpověď = await fetch('http://takove-url-neni'); + } catch(chyba) { *!* - alert(err); // TypeError: failed to fetch + alert(chyba); // TypeError: failed to fetch */!* } } @@ -239,73 +239,73 @@ async function f() { f(); ``` -In the case of an error, the control jumps to the `catch` block. We can also wrap multiple lines: +V případě chyby řízení skočí do bloku `catch`. Můžeme také zabalit více řádků: ```js run async function f() { try { - let response = await fetch('/no-user-here'); - let user = await response.json(); - } catch(err) { - // catches errors both in fetch and response.json - alert(err); + let odpověď = await fetch('/tady-neni-uzivatel'); + let uživatel = await odpověď.json(); + } catch(chyba) { + // zachytává chyby z funkce fetch i z funkce odpověď.json + alert(chyba); } } f(); ``` -If we don't have `try..catch`, then the promise generated by the call of the async function `f()` becomes rejected. We can append `.catch` to handle it: +Pokud nemáme `try..catch`, stane se příslib generovaný voláním asynchronní funkce `f()` zamítnutým. Můžeme připojit `.catch`, abychom to ošetřili: ```js run async function f() { - let response = await fetch('http://no-such-url'); + let odpověď = await fetch('http://takove-url-neni'); } -// f() becomes a rejected promise +// f() se stane zamítnutým příslibem *!* f().catch(alert); // TypeError: failed to fetch // (*) */!* ``` -If we forget to add `.catch` there, then we get an unhandled promise error (viewable in the console). We can catch such errors using a global `unhandledrejection` event handler as described in the chapter . +Jestliže sem zapomeneme přidat `.catch`, získáme neošetřenou chybu příslibu (viditelnou v konzoli). Takové chyby můžeme zachytávat pomocí globálního handleru událostí `unhandledrejection`, popsaného v kapitole . -```smart header="`async/await` and `promise.then/catch`" -When we use `async/await`, we rarely need `.then`, because `await` handles the waiting for us. And we can use a regular `try..catch` instead of `.catch`. That's usually (but not always) more convenient. +```smart header="`async/await` a `promise.then/catch`" +Když používáme `async/await`, potřebujeme `.then` jenom zřídka, neboť `await` nám čekání zpracuje. A místo `.catch` můžeme použít běžné `try..catch`. To je obvykle (ale ne vždy) vhodnější. -But at the top level of the code, when we're outside any `async` function, we're syntactically unable to use `await`, so it's a normal practice to add `.then/catch` to handle the final result or falling-through error, like in the line `(*)` of the example above. +Avšak na nejvyšší úrovni kódu, když jsme mimo jakoukoli funkci s `async`, nemůžeme syntakticky použít `await`, takže je obvyklou praktikou přidat `.then/catch` pro ošetření konečného výsledku nebo vypadnuvší chyby, jako na řádku `(*)` v uvedeném příkladu. ``` -````smart header="`async/await` works well with `Promise.all`" -When we need to wait for multiple promises, we can wrap them in `Promise.all` and then `await`: +````smart header="`async/await` funguje správně s `Promise.all`" +Když potřebujeme čekat na více příslibů, můžeme je zabalit do `Promise.all` a pak volat `await`: ```js -// wait for the array of results -let results = await Promise.all([ +// čekáme na pole výsledků +let výsledky = await Promise.all([ fetch(url1), fetch(url2), ... ]); ``` -In the case of an error, it propagates as usual, from the failed promise to `Promise.all`, and then becomes an exception that we can catch using `try..catch` around the call. +V případě chyby se tato chyba vyvolá jako obvykle, z neúspěšného příslibu do `Promise.all`, a pak se stane výjimkou, kterou můžeme zachytit použitím `try..catch` okolo volání. ```` -## Summary +## Shrnutí -The `async` keyword before a function has two effects: +Klíčové slovo `async` před funkcí má dva efekty: -1. Makes it always return a promise. -2. Allows `await` to be used in it. +1. Způsobí, že funkce vždy vrátí příslib. +2. Umožní v ní použít `await`. -The `await` keyword before a promise makes JavaScript wait until that promise settles, and then: +Klíčové slovo `await` před příslibem přiměje JavaScript čekat, než se příslib usadí, a pak: -1. If it's an error, an exception is generated — same as if `throw error` were called at that very place. -2. Otherwise, it returns the result. +1. Pokud je to chyba, vygeneruje se výjimka -- totéž, jako by přesně na tomto místě bylo voláno `throw chyba`. +2. V opačném případě vrátí výsledek. -Together they provide a great framework to write asynchronous code that is easy to both read and write. +Společně poskytují vynikající rámec pro psaní asynchronního kódu, který je snadné číst i psát. -With `async/await` we rarely need to write `promise.then/catch`, but we still shouldn't forget that they are based on promises, because sometimes (e.g. in the outermost scope) we have to use these methods. Also `Promise.all` is nice when we are waiting for many tasks simultaneously. +S `async/await` potřebujeme psát `příslib.then/catch` jen zřídka, ale stále bychom neměli zapomínat, že tyto metody jsou založeny na příslibech, protože někdy (např. na nejvyšší úrovni kódu) je musíme použít. Když čekáme na mnoho úkolů současně, hodí se i `Promise.all`.