You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/11-async/03-promise-chaining/article.md
+26-26Lines changed: 26 additions & 26 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,13 +1,13 @@
1
1
2
-
# Promises chaining
2
+
# Цепочка промисов
3
3
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>: у нас есть последовательность асинхронных задач, которые должны быть выполнены одна за другой. Например, речь может идти о загрузке скриптов. Как мы можем грамотно реализовать это в коде?
5
5
6
-
Promises provide a couple of recipes to do that.
6
+
Промисы предоставляют пару способов, как это может быть сделано.
7
7
8
-
In this chapter we cover promise chaining.
8
+
В этой главе мы сконцентрируемся на цепочке промисов.
9
9
10
-
It looks like this:
10
+
Это выглядит вот так:
11
11
12
12
```js run
13
13
newPromise(function(resolve, reject) {
@@ -32,23 +32,23 @@ new Promise(function(resolve, reject) {
32
32
});
33
33
```
34
34
35
-
The idea is that the result is passed through the chain of`.then` handlers.
35
+
Идея состоит в том, что результат первого промиса передаётся по цепочке обработчиков`.then`.
36
36
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. ...и так далее.
42
42
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`.
44
44
45
45

46
46
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`.
48
48
49
-
When a handler returns a value, it becomes the result of that promise, so the next `.then` is called with it.
49
+
Когда обработчик возвращает какое-то значение, то оно становится результатом выполнения соответствующего промиса и передаётся в следующий `.then`.
50
50
51
-
To make these words more clear, here's the start of the chain:
51
+
Что проиллюстрировать эти слова, разберём начало цепочки промисов:
52
52
53
53
```js run
54
54
newPromise(function(resolve, reject) {
@@ -64,11 +64,11 @@ new Promise(function(resolve, reject) {
64
64
// .then…
65
65
```
66
66
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)` возвращается значение, то соответствующий промис выполняется успешно, и идущий за ним обработчик получает результат его выполнения.
68
68
69
-
**A classic newbie error: technically we can also add many `.then`to a single promise. This is not chaining.**
69
+
**Классическая ошибка новичков: технически возможно добавить много обработчиков `.then`к единственному промису. Но это не цепочка.**
70
70
71
-
For example:
71
+
Например:
72
72
```js run
73
73
let promise =newPromise(function(resolve, reject) {
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
+
Мы добавили несколько обработчиков к одному промису. Они не передают друг другу результаты своего выполнения, а действуют независимо.
94
94
95
-
Here's the picture (compare it with the chaining above):
95
+
Вот картинка происходящего (сравните это с изображением цепочки промисов выше):
96
96
97
97

98
98
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`.
100
100
101
-
In practice we rarely need multiple handlers for one promise. Chaining is used much more often.
101
+
В реальности весьма редко требуется назначать несколько обработчиков одному промису. А вот цепочка промисов используется куда чаще.
102
102
103
-
## Returning promises
103
+
## Возвращаем промисы
104
104
105
-
Normally, a value returned by a `.then` handler is immediately passed to the next handler. But there's an exception.
105
+
Обычно значение, возвращаемое обработчиком `.then`, сразу же передаётся следующему обработчику. Но есть и исключение.
106
106
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`.
0 commit comments