Skip to content

Commit da25c0e

Browse files
authored
Async/await (#221)
1 parent 807e6e2 commit da25c0e

File tree

8 files changed

+107
-107
lines changed

8 files changed

+107
-107
lines changed

1-js/11-async/08-async-await/01-rewrite-async/solution.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
The notes are below the code:
2+
Примітки наведено під кодом:
33

44
```js run
55
async function loadJson(url) { // (1)
@@ -17,17 +17,17 @@ loadJson('no-such-user.json')
1717
.catch(alert); // Error: 404 (4)
1818
```
1919

20-
Notes:
20+
Примітки:
2121

22-
1. The function `loadJson` becomes `async`.
23-
2. All `.then` inside are replaced with `await`.
24-
3. We can `return response.json()` instead of awaiting for it, like this:
22+
1. Функція `loadJson` стає `async`-функцією.
23+
2. Усі `.then` всередині замінюються на `await`.
24+
3. Ми можемо зробити `return response.json()` замість того, щоб чекати його, наприклад:
2525

2626
```js
2727
if (response.status == 200) {
2828
return response.json(); // (3)
2929
}
3030
```
3131

32-
Then the outer code would have to `await` for that promise to resolve. In our case it doesn't matter.
33-
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.
32+
Тоді зовнішній код повинен був би чекати `await`, поки цей проміс буде виконано. У нашому випадку це не має значення.
33+
4. Помилка, викликана `loadJson`, обробляється `.catch`. Ми не можемо використовувати там `await loadJson(…)`, тому що ми не використовуємо `async`-функцію.

1-js/11-async/08-async-await/01-rewrite-async/task.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

2-
# Rewrite using async/await
2+
# Перепишіть, використовуючи async/await
33

4-
Rewrite this example code from the chapter <info:promise-chaining> using `async/await` instead of `.then/catch`:
4+
Перепишіть цей приклад коду з розділу <info:promise-chaining>, використовуючи `async/await` замість `.then/catch`:
55

66
```js run
77
function loadJson(url) {

1-js/11-async/08-async-await/02-rewrite-async-2/solution.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
There are no tricks here. Just replace `.catch` with `try..catch` inside `demoGithubUser` and add `async/await` where needed:
2+
Тут немає ніяких хитрощів. Просто замініть `.catch` на `try..catch` всередині `demoGithubUser` і додайте `async/await`, де це потрібно:
33

44
```js run
55
class HttpError extends Error {
@@ -19,29 +19,29 @@ async function loadJson(url) {
1919
}
2020
}
2121

22-
// Ask for a user name until github returns a valid user
22+
// Запитуйте ім’я користувача, поки github не поверне дійсного користувача
2323
async function demoGithubUser() {
2424

2525
let user;
2626
while(true) {
27-
let name = prompt("Enter a name?", "iliakan");
27+
let name = prompt("Введіть ім’я?", "iliakan");
2828

2929
try {
3030
user = await loadJson(`https://api.github.com/users/${name}`);
31-
break; // no error, exit loop
31+
break; // помилки немає, виходимо з циклу
3232
} catch(err) {
3333
if (err instanceof HttpError && err.response.status == 404) {
34-
// loop continues after the alert
35-
alert("No such user, please reenter.");
34+
// цикл продовжиться після сповіщення
35+
alert("Такого користувача не існує, будь ласка, введіть ще раз.");
3636
} else {
37-
// unknown error, rethrow
37+
// невідома помилка, перепрокидуємо її
3838
throw err;
3939
}
4040
}
4141
}
4242

4343

44-
alert(`Full name: ${user.name}.`);
44+
alert(`Ім’я та прізвище: ${user.name}.`);
4545
return user;
4646
}
4747

1-js/11-async/08-async-await/02-rewrite-async-2/task.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11

2-
# Rewrite "rethrow" with async/await
2+
# Перепишіть "rethrow", використовуючи async/await
33

4-
Below you can find the "rethrow" example. Rewrite it using `async/await` instead of `.then/catch`.
4+
Нижче ви можете знайти приклад "rethrow". Перепишіть його, використовуючи `async/await` замість `.then/catch`.
55

6-
And get rid of the recursion in favour of a loop in `demoGithubUser`: with `async/await` that becomes easy to do.
6+
І позбудьтеся від рекурсії на користь циклу в `demoGithubUser`: за допомогою `async/await` це буде легко зробити.
77

88
```js run
99
class HttpError extends Error {
@@ -25,18 +25,18 @@ function loadJson(url) {
2525
});
2626
}
2727

28-
// Ask for a user name until github returns a valid user
28+
// Запитуйте ім’я користувача, поки github не поверне дійсного користувача
2929
function demoGithubUser() {
30-
let name = prompt("Enter a name?", "iliakan");
30+
let name = prompt("Введіть ім’я?", "iliakan");
3131

3232
return loadJson(`https://api.github.com/users/${name}`)
3333
.then(user => {
34-
alert(`Full name: ${user.name}.`);
34+
alert(`Ім’я та прізвище: ${user.name}.`);
3535
return user;
3636
})
3737
.catch(err => {
3838
if (err instanceof HttpError && err.response.status == 404) {
39-
alert("No such user, please reenter.");
39+
alert("Такого користувача не існує, будь ласка, введіть ще раз.");
4040
return demoGithubUser();
4141
} else {
4242
throw err;

1-js/11-async/08-async-await/03-async-from-regular/solution.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

2-
That's the case when knowing how it works inside is helpful.
2+
Це той випадок, коли корисно знати, як воно працює всередині.
33

4-
Just treat `async` call as promise and attach `.then` to it:
4+
Просто трактуйте виклик `async` як проміс та додайте до нього `.then`:
55
```js run
66
async function wait() {
77
await new Promise(resolve => setTimeout(resolve, 1000));
@@ -10,7 +10,7 @@ async function wait() {
1010
}
1111

1212
function f() {
13-
// shows 10 after 1 second
13+
// покаже 10 через 1 секунду
1414
*!*
1515
wait().then(result => alert(result));
1616
*/!*
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

2-
# Call async from non-async
2+
# Викличте async-функцію зі "звичайної"
33

4-
We have a "regular" function called `f`. How can you call the `async` function `wait()` and use its result inside of `f`?
4+
У нас є "звичайна" функція під назвою `f`. Як ви можете викликати `async`-функцію `wait()` і використовувати її результат всередині `f`?
55

66
```js
77
async function wait() {
@@ -11,10 +11,10 @@ async function wait() {
1111
}
1212

1313
function f() {
14-
// ...what should you write here?
15-
// we need to call async wait() and wait to get 10
16-
// remember, we can't use "await"
14+
// ...що тут варто написати?
15+
// нам потрібно викликати async-функцію wait() і почекати, щоб отримати 10
16+
// пам’ятайте, ми не можемо використовувати "await"
1717
}
1818
```
1919

20-
P.S. The task is technically very simple, but the question is quite common for developers new to async/await.
20+
P.S. Технічно завдання дуже просте, але дане питання досить поширеним серед розробників, які тільки починають працювати з async/await.

0 commit comments

Comments
 (0)