From d192fb918b0e2aa8869de6dcc59de8464b6e879a Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Fri, 11 Dec 2020 18:59:39 -0500 Subject: dump 2020-12-11 --- .../javascript/asynchronous/async_await/index.html | 42 ++++++++++++---------- 1 file changed, 23 insertions(+), 19 deletions(-) (limited to 'files/ru/learn/javascript/asynchronous') diff --git a/files/ru/learn/javascript/asynchronous/async_await/index.html b/files/ru/learn/javascript/asynchronous/async_await/index.html index 751e08b45e..9882acfa58 100644 --- a/files/ru/learn/javascript/asynchronous/async_await/index.html +++ b/files/ru/learn/javascript/asynchronous/async_await/index.html @@ -1,6 +1,10 @@ --- title: Making asynchronous programming easier with async and await slug: Learn/JavaScript/Asynchronous/Async_await +tags: + - Асинхронность + - Гайд + - Для новичков translation_of: Learn/JavaScript/Asynchronous/Async_await ---
{{LearnSidebar}}
@@ -150,7 +154,7 @@ myFetch().then((blob) => {

Минуточку, а как это все работает ?

-

Вы могли заметить, что мы обернули наш код в функцию и сделали ее асинхронной с помощью acync. Это было обязательно - нам надо создать контейнер, внутри которого будет запускаться асинхронный код и будет возмоность дождаться его результата с помощью await, не блокируя остальной код нашег скрипта.

+

Вы могли заметить, что мы обернули наш код в функцию и сделали ее асинхронной с помощью acync. Это было обязательно - нам надо создать контейнер, внутри которого будет запускаться асинхронный код и будет возмоность дождаться его результата с помощью await, не блокируя остальной код нашего скрипта.

Внутри myFetch() находится код, который слегка напоминает версию на Promise, но есть важные отличия. Вместо того, чтобы писать цепочку блоков .then() мы просто использует ключевое слово await перед вызовом promise-based функции и присваиваем результат в переменную. Ключеовое слово await говорит JavaScript runtime приостановить код в этой строке, не блокируя остальной код скприта за пределами асинхронной функции. Когда вызов promise-based функции будет готов вернуть результат, выполнение продолжится с этой строки дальше.

@@ -225,7 +229,7 @@ myFetch().then((blob) => {

Await и Promise.all()

-

Как вы помните, асинхронные функции построены поверх promises, поэтому они совместимы со всеми возможностями последних. Мы легко можем подождать выполнение Promise.all(), присвоить результат в переменную и все это сделать используя синхронный стиль. Опять, вернемся к an example we saw in our previous article. Откройте пример в соседней вкладке, чтобы лучше понять разницу.

+

Как вы помните, асинхронные функции построены поверх promises, поэтому они совместимы со всеми возможностями последних. Мы легко можем подождать выполнение Promise.all(), присвоить результат в переменную и все это сделать используя синхронный стиль. Опять, вернемся к примеру, рассмотреному в предыдущей статье. Откройте пример в соседней вкладке, чтобы лучше понять разницу.

Версия с async/await (смотрите live demo и source code), сейчас выглядит так:

@@ -300,7 +304,7 @@ displayContent()
Есть подход, который позволяет обойти эту проблему - сохранить все выполняющиеся Promises в переменные, а уже после этого дожидаться (awaiting) их результата. Давайте посмотрим на несколько примеров.

-

We've got two examples available — slow-async-await.html (see source code) and fast-async-await.html (see source code). Both of them start off with a custom promise function that fakes an async process with a setTimeout() call:

+

Мы подготовили два примера  — slow-async-await.html (см. source code) и fast-async-await.html (см. source code). Они оба начинаются с функции возвращающей promise, имитирующей асинхронность процессов при помощи вызова setTimeout():

function timeoutPromise(interval) {
   return new Promise((resolve, reject) => {
@@ -310,13 +314,13 @@ displayContent()
   });
 };
-

Then each one includes a timeTest() async function that awaits three timeoutPromise() calls:

+

Далее в каждом примере есть асинхронная функция  timeTest() ожидающая три вызова timeoutPromise():

async function timeTest() {
   ...
 }
-

Each one ends by recording a start time, seeing how long the timeTest() promise takes to fulfill, then recording an end time and reporting how long the operation took in total:

+

В каждом примере функция записывает время начала исполнения и сколько времерни понадобилось на испольние  timeTest()  промисов, вычитая время в момент запуска функции из времени в момент разрешения обещаний:

let startTime = Date.now();
 timeTest().then(() => {
@@ -325,9 +329,9 @@ timeTest().then(() => {
   alert("Time taken in milliseconds: " + timeTaken);
 })
-

It is the timeTest() function that differs in each case.

+

Далее представленна асинхронная функция timeTest() различная для каждого из примеров.

-

In the slow-async-await.html example, timeTest() looks like this:

+

В случае с медленным примером slow-async-await.html, timeTest() выглядит:

async function timeTest() {
   await timeoutPromise(3000);
@@ -335,9 +339,9 @@ timeTest().then(() => {
   await timeoutPromise(3000);
 }
-

Here we simply await all three timeoutPromise() calls directly, making each one alert for 3 seconds. Each subsequent one is forced to wait until the last one finished — if you run the first example, you'll see the alert box reporting a total run time of around 9 seconds.

+

Здесь мы просто ждем все три  timeoutPromise() напрямую, блокируя выполнение на данного блока на 3 секунды прии каждом вызове. Все последующие вызовы вынуждены ждать пока разрешится предыдущий. Если вы запустите первый пример (slow-async-await.html) вы увидите alert сообщающий время выполнения около 9 секунд. 

-

In the fast-async-await.html example, timeTest() looks like this:

+

Во втором  fast-async-await.html примере, функция timeTest() выглядит как:

async function timeTest() {
   const timeoutPromise1 = timeoutPromise(3000);
@@ -349,17 +353,17 @@ timeTest().then(() => {
   await timeoutPromise3;
 }
-

Here we store the three Promise objects in variables, which has the effect of setting off their associated processes all running simultaneously.

+

В данном случае мы храмим три объекта Promise в переменных,  каждый из которых может разрешиться независимо от других.

-

Next, we await their results — because the promises all started processing at essentially the same time, the promises will all fulfill at the same time; when you run the second example, you'll see the alert box reporting a total run time of just over 3 seconds!

+

Ниже мы ожидаем разрешения промисов из объекта в результат, так как они были запущенны одновременно, блокируя поток, то и разрешатся одновременно. Если вы запустите вроторой приимер вы увидите alert, сообщающий время выполнения около 3 секунд.

-

You'll have to test your code carefully, and bear this in mind if performance starts to suffer.

+

Важно не забывать о быстродействии применяя await, проверяйте количество блокировок.

-

Another minor inconvenience is that you have to wrap your awaited promises inside an async function.

+

+

Async/await class methods

-

Async/await class methods

-

As a final note before we move on, you can even add async in front of class/object methods to make them return promises, and await promises inside them. Take a look at the ES class code we saw in our object-oriented JavaScript article, and then look at our modified version with an async method:

+

В качестве последнего замечания, вы можете использовать  async  перед методами классов или объектов, вынуждая их возвращать promises. А также  await внутри методов объявленных такиим образом. Посмотрите на пример ES class code, который мы наблюдали в статье  object-oriented JavaScript,  и сравниете его с модифицированной (асинхронной) async версией ниже:

class Person {
   constructor(first, last, age, gender, interests) {
@@ -383,19 +387,19 @@ timeTest().then(() => {
 
 let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
-

The first class method could now be used something like this:

+

Первый метод класса теперь можно использовать таким образом:

han.greeting().then(console.log);
-

Browser support

+

Browser support (Поддержка браузерами)

One consideration when deciding whether to use async/await is support for older browsers. They are available in modern versions of most browsers, the same as promises; the main support problems come with Internet Explorer and Opera Mini.

If you want to use async/await but are concerned about older browser support, you could consider using the BabelJS library — this allows you to write your applications using the latest JavaScript and let Babel figure out what changes if any are needed for your user’s browsers. On encountering a browser that does not support async/await, Babel's polyfill can automatically provide fallbacks that work in older browsers.

-

Conclusion

+

Заключение

-

And there you have it — async/await provide a nice, simplified way to write async code that is simpler to read and maintain. Even with browser support being more limited than other async code mechanisms at the time of writing, it is well worth learning and considering for use, both for now and in the future.

+

Вот пожалуй и все - async/await позволяют писать асинхронный код, который легче читать и поддерживать. Даже учитывая, что поддержка со стороны браузеров несколько хуже, чем у promise.then, все же стоит обратить на него внимание.

{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Choosing_the_right_approach", "Learn/JavaScript/Asynchronous")}}

-- cgit v1.2.3-54-g00ecf