Skip to content

Commit 53f306c

Browse files
committed
часть перевода
1 parent de3044b commit 53f306c

File tree

3 files changed

+28
-28
lines changed

3 files changed

+28
-28
lines changed

1-js/11-async/03-promise-chaining/article.md

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

2-
# Promises chaining
2+
# Цепочка промисов
33

4-
Let's return to the problem mentioned in the chapter <info:callbacks>: we have a sequence of asynchronous tasks to be done one after another. For instance, loading scripts. How can we code it well?
4+
Давайте вернёмся к ситуации из главы <info:callbacks>: у нас есть последовательность асинхронных задач, которые должны быть выполнены одна за другой. Например, речь может идти о загрузке скриптов. Как мы можем грамотно реализовать это в коде?
55

6-
Promises provide a couple of recipes to do that.
6+
Промисы предоставляют пару способов, как это может быть сделано.
77

8-
In this chapter we cover promise chaining.
8+
В этой главе мы сконцентрируемся на цепочке промисов.
99

10-
It looks like this:
10+
Это выглядит вот так:
1111

1212
```js run
1313
new Promise(function(resolve, reject) {
@@ -32,23 +32,23 @@ new Promise(function(resolve, reject) {
3232
});
3333
```
3434

35-
The idea is that the result is passed through the chain of `.then` handlers.
35+
Идея состоит в том, что результат первого промиса передаётся по цепочке обработчиков `.then`.
3636

37-
Here the flow is:
38-
1. The initial promise resolves in 1 second `(*)`,
39-
2. Then the `.then` handler is called `(**)`.
40-
3. The value that it returns is passed to the next `.then` handler `(***)`
41-
4. ...and so on.
37+
Поток выполнения такой:
38+
1. Начальный промис успешно выполняется через 1 секунду `(*)`,
39+
2. Затем вызывается обработчик `.then` `(**)`.
40+
3. Возвращаемое им значение передаётся дальше в следующий обработчик `.then` `(***)`
41+
4. ...и так далее.
4242

43-
As the result is passed along the chain of handlers, we can see a sequence of `alert` calls: `1` -> `2` -> `4`.
43+
В итоге результат передаётся по цепочке обработчиков, и мы видим несколько `alert` подряд, которые выводят: `1` -> `2` -> `4`.
4444

4545
![](promise-then-chain.png)
4646

47-
The whole thing works, because a call to `promise.then` returns a promise, so that we can call the next `.then` on it.
47+
Всё это работает, потому что вызов `promise.then` тоже возвращает промис, так что мы можем вызвать на нём следующий `.then`.
4848

49-
When a handler returns a value, it becomes the result of that promise, so the next `.then` is called with it.
49+
Когда обработчик возвращает какое-то значение, то оно становится результатом выполнения соответствующего промиса и передаётся в следующий `.then`.
5050

51-
To make these words more clear, here's the start of the chain:
51+
Что проиллюстрировать эти слова, разберём начало цепочки промисов:
5252

5353
```js run
5454
new Promise(function(resolve, reject) {
@@ -64,11 +64,11 @@ new Promise(function(resolve, reject) {
6464
// .then…
6565
```
6666

67-
The value returned by `.then` is a promise, that's why we are able to add another `.then` at `(2)`. When the value is returned in `(1)`, that promise becomes resolved, so the next handler runs with the value.
67+
Значение, возвращаемое `.then`, является промисом, и поэтому можно добавить другой обработчик `.then` в строке `(2)`. Когда из строки `(1)` возвращается значение, то соответствующий промис выполняется успешно, и идущий за ним обработчик получает результат его выполнения.
6868

69-
**A classic newbie error: technically we can also add many `.then` to a single promise. This is not chaining.**
69+
**Классическая ошибка новичков: технически возможно добавить много обработчиков `.then` к единственному промису. Но это не цепочка.**
7070

71-
For example:
71+
Например:
7272
```js run
7373
let promise = new Promise(function(resolve, reject) {
7474
setTimeout(() => resolve(1), 1000);
@@ -90,23 +90,23 @@ promise.then(function(result) {
9090
});
9191
```
9292

93-
What we did here is just several handlers to one promise. They don't pass the result to each other, instead they process it independently.
93+
Мы добавили несколько обработчиков к одному промису. Они не передают друг другу результаты своего выполнения, а действуют независимо.
9494

95-
Here's the picture (compare it with the chaining above):
95+
Вот картинка происходящего (сравните это с изображением цепочки промисов выше):
9696

9797
![](promise-then-many.png)
9898

99-
All `.then` on the same promise get the same result -- the result of that promise. So in the code above all `alert` show the same: `1`.
99+
Все обработчики `.then` на одном и том же промисе получают одно и то же значение -- результат выполнения того самого промиса. Таким образом, в коде выше все `alert` показывают одно и то же: `1`.
100100

101-
In practice we rarely need multiple handlers for one promise. Chaining is used much more often.
101+
В реальности весьма редко требуется назначать несколько обработчиков одному промису. А вот цепочка промисов используется куда чаще.
102102

103-
## Returning promises
103+
## Возвращаем промисы
104104

105-
Normally, a value returned by a `.then` handler is immediately passed to the next handler. But there's an exception.
105+
Обычно значение, возвращаемое обработчиком `.then`, сразу же передаётся следующему обработчику. Но есть и исключение.
106106

107-
If the returned value is a promise, then the further execution is suspended until it settles. After that, the result of that promise is given to the next `.then` handler.
107+
Если возвращается промис, то дальнейшее исполнение скрипта приостанавливается до тех пор, пока промис не выполнится. После этого результат того промиса передаётся дальше следующему обработчику `.then`.
108108

109-
For instance:
109+
Например:
110110

111111
```js run
112112
new Promise(function(resolve, reject) {
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
function getMessage() {
2-
return "Hello, world!";
2+
return "Привет, мир!";
33
}

1-js/11-async/03-promise-chaining/head.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
script.src = src;
66

77
script.onload = () => resolve(script);
8-
script.onerror = () => reject(new Error("Script load error: " + src));
8+
script.onerror = () => reject(new Error("Ошибка загрузки скрипта: " + src));
99

1010
document.head.append(script);
1111
});

0 commit comments

Comments
 (0)