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: control-flow/index.md
+32-8Lines changed: 32 additions & 8 deletions
Original file line number
Diff line number
Diff line change
@@ -23,7 +23,7 @@ This is not what we want. We'll have to go wash our hands again. In production c
23
23
24
24
Node generally runs in one single thread and any _blocking_ code will be run in sequence, with _non-blocking_ code having the potential to run _asynchronously_.
25
25
26
-
Thankfully Node offers 3 approaches we can use to control the order in which our code executes. _Callbacks_, _promises_ and _async/await_. Let's take a look at each.
26
+
Thankfully Node offers 3 asynchronous approaches we can use to control the order in which our code executes. _Callbacks_, _promises_ and _async/await_. Let's take a look at each.
27
27
28
28
## Callbacks
29
29
@@ -71,7 +71,14 @@ This might be reasonable in simple situations but it's easy for callbacks to get
71
71
To show many responses, consider the following code. If we ran them beside each other, the output would not be reliable.
72
72
73
73
```
74
-
// ... replacing the last two lines of the previous example
74
+
function randomDelayedResponse(text) {
75
+
// Using a timeout here for the sake of simulating an external request
@@ -116,7 +123,7 @@ Let's look at one such alternative.
116
123
To avoid this callback hell, we can use a different structure called _promises_. A promise is a function that returns a _resolved_ response which we can chain using `then`, or a _rejected_ response which we can `catch`. It follows this pattern:
117
124
118
125
```
119
-
runOutPromise() // returns a response
126
+
runOurPromise() // returns a response
120
127
.then(response => {
121
128
return foo; // this could optionally be another promise
122
129
})
@@ -135,10 +142,10 @@ function randomDelayedResponse(text, callback) {
resolve(text); // Replacing the callback with "resolve"
145
+
if (!text) {
146
+
reject('No text provided!'); // Reject when there is no text provided
140
147
}
141
-
reject('No text provided!'); // Reject when there is an error
148
+
resolve(text); // Replacing the callback with "resolve"
142
149
}, timeOut);
143
150
});
144
151
}
@@ -176,7 +183,17 @@ Promises remove the nesting and give us easier to read code. Let's look at a thi
176
183
The third approach is built on top of the existing _promises_ approach and results in even simpler code. With `async` and `await` we can write code that feels a lot more like our usual top-down code. It works by telling our commands to wait when we need them to. Let's rewrite our _who will win?_ example from above.
0 commit comments