Skip to content

Async/await #221

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

Merged
merged 1 commit into from
Nov 23, 2021
Merged
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
14 changes: 7 additions & 7 deletions 1-js/11-async/08-async-await/01-rewrite-async/solution.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

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

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

Notes:
Примітки:

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. Функція `loadJson` стає `async`-функцією.
2. Усі `.then` всередині замінюються на `await`.
3. Ми можемо зробити `return response.json()` замість того, щоб чекати його, наприклад:

```js
if (response.status == 200) {
return response.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.
Тоді зовнішній код повинен був би чекати `await`, поки цей проміс буде виконано. У нашому випадку це не має значення.
4. Помилка, викликана `loadJson`, обробляється `.catch`. Ми не можемо використовувати там `await loadJson(…)`, тому що ми не використовуємо `async`-функцію.
4 changes: 2 additions & 2 deletions 1-js/11-async/08-async-await/01-rewrite-async/task.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

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

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

```js run
function loadJson(url) {
Expand Down
16 changes: 8 additions & 8 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,5 +1,5 @@

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

```js run
class HttpError extends Error {
Expand All @@ -19,29 +19,29 @@ async function loadJson(url) {
}
}

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

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

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


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

Expand Down
14 changes: 7 additions & 7 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,9 +1,9 @@

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

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

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

```js run
class HttpError extends Error {
Expand All @@ -25,18 +25,18 @@ function loadJson(url) {
});
}

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

return loadJson(`https://api.github.com/users/${name}`)
.then(user => {
alert(`Full name: ${user.name}.`);
alert(`Ім’я та прізвище: ${user.name}.`);
return user;
})
.catch(err => {
if (err instanceof HttpError && err.response.status == 404) {
alert("No such user, please reenter.");
alert("Такого користувача не існує, будь ласка, введіть ще раз.");
return demoGithubUser();
} else {
throw err;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

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

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

function f() {
// shows 10 after 1 second
// покаже 10 через 1 секунду
*!*
wait().then(result => alert(result));
*/!*
Expand Down
12 changes: 6 additions & 6 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,7 +1,7 @@

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

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

```js
async function wait() {
Expand All @@ -11,10 +11,10 @@ async function wait() {
}

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

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