GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Async/await by Nordtonito · Pull Request #221 · javascript-tutorial/uk.javascript.info

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.

Sign up for GitHub

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
tarasyyyk merged 1 commit into javascript-tutorial:master from Nordtonito:master
Nov 23, 2021

Uh oh!

There was an error while loading. Please reload this page.

Merged

Async/await #221

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
1 commit
Select commit
f664f0c
Async/await
Nordtonito Nov 18, 2021
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

14 changes: 7 additions & 7 deletions 14 1-js/11-async/08-async-await/01-rewrite-async/solution.md
Show comments
View file
Open in desktop
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:
Примітки:
Comment thread
Nordtonito marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.


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 4 1-js/11-async/08-async-await/01-rewrite-async/task.md
Show comments
View file
Open in desktop
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 16 1-js/11-async/08-async-await/02-rewrite-async-2/solution.md
Show comments
View file
Open in desktop
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 14 1-js/11-async/08-async-await/02-rewrite-async-2/task.md
Show comments
View file
Open in desktop
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
6 changes: 3 additions & 3 deletions 6 1-js/11-async/08-async-await/03-async-from-regular/solution.md
Show comments
View file
Open in desktop
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 12 1-js/11-async/08-async-await/03-async-from-regular/task.md
Show comments
View file
Open in desktop
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
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.