Skip to content

Async/await #199

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions 1-js/11-async/08-async-await/01-rewrite-async/solution.md
Original file line number Diff line number Diff line change
@@ -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`.
18 changes: 9 additions & 9 deletions 1-js/11-async/08-async-await/01-rewrite-async/task.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@

# Rewrite using async/await
# Přepište za použití async/await

Rewrite this example code from the chapter <info:promise-chaining> using `async/await` instead of `.then/catch`:
Přepište tento příklad kódu z kapitoly <info:promise-chaining> 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
```
52 changes: 26 additions & 26 deletions 1-js/11-async/08-async-await/02-rewrite-async-2/solution.md
Original file line number Diff line number Diff line change
@@ -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();
```
52 changes: 26 additions & 26 deletions 1-js/11-async/08-async-await/02-rewrite-async-2/task.md
Original file line number Diff line number Diff line change
@@ -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();
```
10 changes: 5 additions & 5 deletions 1-js/11-async/08-async-await/03-async-from-regular/solution.md
Original file line number Diff line number Diff line change
@@ -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));
*/!*
}

Expand Down
14 changes: 7 additions & 7 deletions 1-js/11-async/08-async-await/03-async-from-regular/task.md
Original file line number Diff line number Diff line change
@@ -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á.
Loading