Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
otmon76 merged 1 commit intojavascript-tutorial:masterfromotmon76:1.11.8
Jun 4, 2025
Merged
Show file tree
Hide file tree
Changes fromall 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 deletions1-js/11-async/08-async-await/01-rewrite-async/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@

The notes are below the code:
Poznámky jsou pod kódem:

```js run
async functionloadJson(url) { // (1)
letresponse = await fetch(url); // (2)
async functionnačtiJson(url) { // (1)
letodpověď = await fetch(url); // (2)

if (response.status == 200) {
let json = awaitresponse.json(); // (3)
if (odpověď.status == 200) {
let json = awaitodpověď.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 `returnresponse.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 `returnodpověď.json()`místo čekání na tuto funkci, například:

```js
if (response.status == 200) {
returnresponse.json(); // (3)
if (odpověď.status == 200) {
returnodpověď.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 `awaitloadJson(…)` 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 `awaitnačtiJson(…)`, protože nejsme uvnitř funkce s `async`.
18 changes: 9 additions & 9 deletions1-js/11-async/08-async-await/01-rewrite-async/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff 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
functionloadJson(url) {
functionnačtiJson(url) {
return fetch(url)
.then(response => {
if (response.status == 200) {
returnresponse.json();
.then(odpověď => {
if (odpověď.status == 200) {
returnodpověď.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 deletions1-js/11-async/08-async-await/02-rewrite-async-2/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff 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
classHttpError extends Error {
constructor(response) {
super(`${response.status}for ${response.url}`);
this.name = 'HttpError';
this.response =response;
classChybaHttp extends Error {
constructor(odpověď) {
super(`${odpověď.status}pro ${odpověď.url}`);
this.name = 'ChybaHttp';
this.odpověď =odpověď;
}
}

async functionloadJson(url) {
letresponse = await fetch(url);
if (response.status == 200) {
returnresponse.json();
async functionnačtiJson(url) {
letodpověď = await fetch(url);
if (odpověď.status == 200) {
returnodpověď.json();
} else {
throw newHttpError(response);
throw newChybaHttp(odpověď);
}
}

//Ask for a user name until github returns a valid user
async functiondemoGithubUser() {
//Ptáme se na uživatelské jméno, dokud GitHub nevrátí platného uživatele
async functiondemoUživatelGitHubu() {

letuser;
letuživatel;
while(true) {
letname = prompt("Enter a name?", "iliakan");
letjméno = prompt("Zadejte jméno", "iliakan");

try {
user = awaitloadJson(`https://api.github.com/users/${name}`);
break; //no error, exit loop
} catch(err) {
if (err instanceofHttpError &&err.response.status == 404) {
//loop continues after the alert
alert("No such user, please reenter.");
uživatel = awaitnačtiJson(`https://api.github.com/users/${jméno}`);
break; //žádná chyba, opustíme cyklus
} catch(chyba) {
if (chyba instanceofChybaHttp &&chyba.odpověď.status == 404) {
//po alertu bude cyklus pokračovat
alert("Takový uživatel neexistuje, prosím zadejte znovu.");
} else {
//unknown error, rethrow
throwerr;
//neznámá chyba, vyvoláme ji znovu
throwchyba;
}
}
}


alert(`Full name: ${user.name}.`);
returnuser;
alert(`Celé jméno: ${uživatel.name}.`);
returnuživatel;
}

demoGithubUser();
demoUživatelGitHubu();
```
52 changes: 26 additions & 26 deletions1-js/11-async/08-async-await/02-rewrite-async-2/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff 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 easytodo.
A ve funkci `demoUživatelGitHubu` se zbavte rekurze ve prospěch cyklu: s `async/await` tobude lehké.

```js run
classHttpError extends Error {
constructor(response) {
super(`${response.status}for ${response.url}`);
this.name = 'HttpError';
this.response =response;
classChybaHttp extends Error {
constructor(odpověď) {
super(`${odpověď.status}pro ${odpověď.url}`);
this.name = 'ChybaHttp';
this.odpověď =odpověď;
}
}

functionloadJson(url) {
functionnačtiJson(url) {
return fetch(url)
.then(response => {
if (response.status == 200) {
returnresponse.json();
.then(odpověď => {
if (odpověď.status == 200) {
returnodpověď.json();
} else {
throw newHttpError(response);
throw newChybaHttp(odpověď);
}
});
}

//Ask for a user name until github returns a valid user
functiondemoGithubUser() {
letname = prompt("Enter a name?", "iliakan");
//Ptáme se na uživatelské jméno, dokud GitHub nevrátí platného uživatele
functiondemoUživatelGitHubu() {
letjméno = prompt("Zadejte jméno", "iliakan");

returnloadJson(`https://api.github.com/users/${name}`)
.then(user => {
alert(`Full name: ${user.name}.`);
returnuser;
returnnačtiJson(`https://api.github.com/users/${jméno}`)
.then(uživatel => {
alert(`Celé jméno: ${uživatel.name}.`);
returnuživatel;
})
.catch(err => {
if (err instanceofHttpError &&err.response.status == 404) {
alert("No such user, please reenter.");
returndemoGithubUser();
.catch(chyba => {
if (chyba instanceofChybaHttp &&chyba.odpověď.status == 404) {
alert("Takový uživatel neexistuje, prosím zadejte znovu.");
returndemoUživatelGitHubu();
} else {
throwerr;
throwchyba;
}
});
}

demoGithubUser();
demoUživatelGitHubu();
```
View file
Open in desktop
Original file line numberDiff line numberDiff 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 functionwait() {
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 deletions1-js/11-async/08-async-await/03-async-from-regular/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff 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 functionwait() {
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 toasync/await.
P.S.Tento úkol je technicky velmi jednoduchý, ale tato otázka je u vývojářů, kteří sasync/await teprve začínají, vcelku běžná.
Loading

[8]ページ先頭

©2009-2025 Movatter.jp