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
In the code above, all `.then`are on the same promise, so all of them get the same result -- the result of that promise. And all `alert` show the same: 1.
69
+
...But that's a totally different thing. All `.then` on the same promiseget the same result -- the result of that promise:
70
70
71
71

72
72
73
-
If we want to use the value returned by a handler of `.then`, then we should add a new `.then` after it (to chain).
73
+
So in the code above all `alert` show the same: 1.
74
+
75
+
In practice chaining is used far more often than adding many handlers to the same promise.
74
76
75
77
## Returning promises
76
78
77
-
Normally, the value returned by a handler is passed to the next `.then`. But there's an exception. If the returned value is a promise, then further execution is suspended till it settles. And then the result of that promise is used.
79
+
Normally, a value returned by a handler is passed to the next `.then`. But there's an exception. If the returned value is a promise, then further execution is suspended till it settles. And then the result of that promise is given to the next `.then`.
78
80
79
-
Let's see it in action here:
81
+
For instance:
80
82
81
83
```js run
82
84
newPromise(function(resolve, reject) {
@@ -110,11 +112,11 @@ new Promise(function(resolve, reject) {
110
112
});
111
113
```
112
114
113
-
Now we have the same 1 -> 2 > 4 output, but with 1 second delay between each.
115
+
Here each `.then` returns `new Promise(…)`. JavaScript awaits for it to settle and then passes on the result.
114
116
115
-
When we return `new Promise(…)`, the next `.then` in the chain is executed when it settles and gets its result.
117
+
So the output is again 1 -> 2 > 4, but with 1 second delay between `alert` calls.
116
118
117
-
Let's use it with `loadScript` to load multiple scripts one by one, in sequence:
119
+
Let's use it with `loadScript` to load scripts one by one, in sequence:
0 commit comments