Skip to content

Commit 482ec27

Browse files
authored
Merge pull request javascript-tutorial#418 from davegregg/master
Rewordings and corrections to Promise Basics
2 parents d8d5086 + dfa4451 commit 482ec27

File tree

1 file changed

+69
-55
lines changed

1 file changed

+69
-55
lines changed

6-async/02-promise-basics/article.md

Lines changed: 69 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
# Promise
22

3-
Imagine that you're a top singer, and fans ask for your next upcoming single day and night.
3+
Imagine that you're a top singer, and fans ask day and night for your upcoming single.
44

5-
To get a relief, you promise to send it to them when it's published. You give your fans a list. They can fill in their coordinates, so that when the song becomes available, all subscribed parties instantly get it. And if something goes very wrong, so that the song won't be published ever, then they are also to be notified.
5+
To get some relief, you promise to send it to them when it's published. You give your fans a list to which they can subscribe for updates. They can fill in their email addresses, so that when the song becomes available, all subscribed parties instantly receive it. And even if something goes very wrong, say, if plans to publish the song are cancelled, they will still be notified.
66

77
Everyone is happy: you, because the people don't crowd you any more, and fans, because they won't miss the single.
88

9-
That was a real-life analogy for things we often have in programming:
9+
This is a real-life analogy for things we often have in programming:
1010

11-
1. A "producing code" that does something and needs time. For instance, it loads a remote script. That's a "singer".
12-
2. A "consuming code" wants the result when it's ready. Many functions may need that result. These are "fans".
13-
3. A *promise* is a special JavaScript object that links them together. That's a "list". The producing code creates it and gives to everyone, so that they can subscribe for the result.
11+
1. A "producing code" that does something and takes time. For instance, the code loads a remote script. That's a "singer".
12+
2. A "consuming code" that wants the result of the "producing code" once it's ready. Many functions (in your "consuming code") may need that result. These are the "fans".
13+
3. A *promise* is a special JavaScript object that links the "producing code" and the "consuming code" together. In terms of our analogy: this is the "subscription list". The "producing code" takes whatever time it needs to produce the promised result, and the "promise" makes that result available to all of the subscribed code when it's ready.
1414

15-
The analogy isn't very accurate, because JavaScript promises are more complex than a simple list: they have additional features and limitations. But still they are alike.
15+
The analogy isn't terribly accurate, because JavaScript promises are more complex than a simple subscription list: they have additional features and limitations. But this will serve for an introduction.
1616

1717
The constructor syntax for a promise object is:
1818

@@ -22,25 +22,25 @@ let promise = new Promise(function(resolve, reject) {
2222
});
2323
```
2424

25-
The function passed to `new Promise` is called *executor*. When the promise is created, it's called automatically. It contains the producing code, that should eventually finish with a result. In terms of the analogy above, the executor is a "singer".
25+
The function passed to `new Promise` is called the *executor*. When the promise is created, this executor function is called (or, run) automatically. It contains the producing code, that should eventually produce a result. In terms of the analogy above: the executor is the "singer".
2626

2727
The resulting `promise` object has internal properties:
2828

29-
- `state` -- initially is "pending", then changes to "fulfilled" or "rejected",
30-
- `result` -- an arbitrary value, initially `undefined`.
29+
- `state` initially "pending", then changes to either "fulfilled" or "rejected",
30+
- `result` an arbitrary value of your choosing, initially `undefined`.
3131

32-
When the executor finishes the job, it should call one of:
32+
When the executor finishes the job, it should call one of the following functions:
3333

34-
- `resolve(value)` -- to indicate that the job finished successfully:
34+
- `resolve(value)` to indicate that the job finished successfully:
3535
- sets `state` to `"fulfilled"`,
3636
- sets `result` to `value`.
37-
- `reject(error)` -- to indicate that an error occurred:
37+
- `reject(error)` to indicate that an error occurred:
3838
- sets `state` to `"rejected"`,
3939
- sets `result` to `error`.
4040

4141
![](promise-resolve-reject.png)
4242

43-
Here's a simple executor, to gather that all together:
43+
To gather all of that together: here's an example of a Promise constructor and a simple executor function with its "producing code" (the `setTimeout`):
4444

4545
```js run
4646
let promise = new Promise(function(resolve, reject) {
@@ -56,16 +56,16 @@ let promise = new Promise(function(resolve, reject) {
5656

5757
We can see two things by running the code above:
5858

59-
1. The executor is called automatically and immediately (by `new Promise`).
60-
2. The executor receives two arguments: `resolve` and `reject` -- these functions come from JavaScript engine. We don't need to create them. Instead the executor should call them when ready.
59+
1. The executor is called automatically and immediately (by the `new Promise`).
60+
2. The executor receives two arguments: `resolve` and `reject` these functions are pre-defined by the JavaScript engine. So we don't need to create them. Instead, we should write the executor to call them when ready.
6161

62-
After one second of thinking the executor calls `resolve("done")` to produce the result:
62+
After one second of "processing" the executor calls `resolve("done")` to produce the result:
6363

6464
![](promise-resolve-1.png)
6565

66-
That was an example of the "successful job completion".
66+
That was an example of a successful job completion, a "fulfilled promise".
6767

68-
And now an example where the executor rejects promise with an error:
68+
And now an example of the executor rejecting the promise with an error:
6969

7070
```js
7171
let promise = new Promise(function(resolve, reject) {
@@ -76,12 +76,12 @@ let promise = new Promise(function(resolve, reject) {
7676

7777
![](promise-reject-1.png)
7878

79-
To summarize, the executor should do a job (something that takes time usually) and then call `resolve` or `reject` to change the state of the corresponding promise object.
79+
To summarize, the executor should do a job (something that takes time usually) and then call `resolve` or `reject` to change the state of the corresponding Promise object.
8080

81-
The promise that is either resolved or rejected is called "settled", as opposed to a "pending" promise.
81+
The Promise that is either resolved or rejected is called "settled", as opposed to a "pending" Promise.
8282

83-
````smart header="There can be only one result or an error"
84-
The executor should call only one `resolve` or `reject`. The promise state change is final.
83+
````smart header="There can be only a single result or an error"
84+
The executor should call only one `resolve` or `reject`. The promise's state change is final.
8585
8686
All further calls of `resolve` and `reject` are ignored:
8787
@@ -94,46 +94,53 @@ let promise = new Promise(function(resolve, reject) {
9494
});
9595
```
9696
97-
The idea is that a job done by the executor may have only one result or an error. In programming, there exist other data structures that allow many "flowing" results, for instance streams and queues. They have their own advantages and disadvantages versus promises. They are not supported by JavaScript core and lack certain language features that promises provide, we don't cover them here to concentrate on promises.
97+
The idea is that a job done by the executor may have only one result or an error.
9898
99-
Also if we call `resolve/reject` with more then one argument -- only the first argument is used, the next ones are ignored.
99+
Further, `resolve`/`reject` expect only one argument and will ignore additional arguments.
100100
````
101101

102102
```smart header="Reject with `Error` objects"
103-
Technically we can call `reject` (just like `resolve`) with any type of argument. But it's recommended to use `Error` objects in `reject` (or inherit from them). The reasoning for that will become obvious soon.
103+
Technically, we can pass any type of argument to `reject` (just like `resolve`). But it is recommended to use `Error` objects (or objects that inherit from `Error`). The reasoning for that will soon become apparent.
104104
```
105105
106-
````smart header="Resolve/reject can be immediate"
107-
In practice an executor usually does something asynchronously and calls `resolve/reject` after some time, but it doesn't have to. We can call `resolve` or `reject` immediately, like this:
106+
````smart header="Immediately calling `resolve`/`reject`"
107+
In practice, an executor usually does something asynchronously and calls `resolve`/`reject` after some time, but it doesn't have to. We can call `resolve` or `reject` immediately, like this:
108108
109109
```js
110110
let promise = new Promise(function(resolve, reject) {
111111
resolve(123); // immediately give the result: 123
112112
});
113113
```
114114

115-
For instance, it happens when we start to do a job and then see that everything has already been done. Technically that's fine: we have a resolved promise right now.
115+
For instance, this might happen when we start to do a job but then see that everything has already been completed. That is fine: we immediately have a resolved Promise.
116116
````
117117
118118
```smart header="The `state` and `result` are internal"
119-
Properties `state` and `result` of a promise object are internal. We can't directly access them from our code, but we can use methods `.then/catch` for that, they are described below.
119+
The properties `state` and `result` of the Promise object are internal. We can't directly access them from our "consuming code". We can use the methods `.then`/`.catch` for that. They are described below.
120120
```
121121
122-
## Consumers: ".then" and ".catch"
123-
124-
A promise object serves as a link between the producing code (executor) and the consuming functions -- those that want to receive the result/error. Consuming functions can be registered using methods `promise.then` and `promise.catch`.
122+
## Consumers: `.then and `.catch`
125123
124+
A Promise object serves as a link between the executor (the "producing code" or "singer) and the consuming functions (the "fans"), which will receive the result or error. Consuming functions can be registered (subscribed) using the methods `.then` and `.catch`.
126125
127126
The syntax of `.then` is:
128127
129128
```js
130129
promise.then(
131-
function(result) { /* handle a successful result */ },
132-
function(error) { /* handle an error */ }
130+
function(result) { *!*/* handle a successful result */*/!* },
131+
function(error) { *!*/* handle an error */*/!* }
133132
);
134133
```
135134
136-
The first function argument runs when the promise is resolved and gets the result, and the second one -- when it's rejected and gets the error.
135+
The first function argument:
136+
137+
1. runs when the Promise is resolved, and
138+
2. receives the result.
139+
140+
The second function argument:
141+
142+
1. runs when the Promise is rejected, and
143+
2. receives the error.
137144
138145
For instance:
139146
@@ -151,7 +158,7 @@ promise.then(
151158
);
152159
```
153160
154-
In case of a rejection:
161+
In the case of a rejection:
155162
156163
```js run
157164
let promise = new Promise(function(resolve, reject) {
@@ -167,7 +174,7 @@ promise.then(
167174
);
168175
```
169176
170-
If we're interested only in successful completions, then we can provide only one argument to `.then`:
177+
If we're interested only in successful completions, then we can provide only one function argument to `.then`:
171178
172179
```js run
173180
let promise = new Promise(resolve => {
@@ -179,7 +186,7 @@ promise.then(alert); // shows "done!" after 1 second
179186
*/!*
180187
```
181188
182-
If we're interested only in errors, then we can use `.then(null, function)` or an "alias" to it: `.catch(function)`
189+
If we're interested only in errors, then we can use `.catch(errorHandlingFunction)`, which is exactly the same as `.then(null, errorHandlingFunction)`.
183190
184191
185192
```js run
@@ -208,32 +215,39 @@ promise.then(alert); // done! (shows up right now)
208215
That's handy for jobs that may sometimes require time and sometimes finish immediately. The handler is guaranteed to run in both cases.
209216
````
210217

211-
````smart header="Handlers of `.then/catch` are always asynchronous"
212-
To be even more precise, when `.then/catch` handler should execute, it first gets into an internal queue. The JavaScript engine takes handlers from the queue and executes when the current code finishes, similar to `setTimeout(..., 0)`.
218+
````smart header="Handlers of `.then`/`.catch` are always asynchronous"
219+
Even when the Promise is immediately resolved, code which occurs on lines *below* your `.then`/`.catch` may still execute first.
213220

214-
In other words, when `.then(handler)` is going to trigger, it does something like `setTimeout(handler, 0)` instead.
221+
When it is time for the function you've passed to `.then`/`.catch` to execute, the JavaScript engine puts it at the end of an internal execution queue.
215222

216-
In the example below the promise is immediately resolved, so `.then(alert)` triggers right now: the `alert` call is queued and runs immediately after the code finishes.
223+
The JavaScript engine doesn't wait very long for an operation to finish before moving on to do other things. Everything is racing to get done. So as you gain experience, you will encounter situations where some lines of code are still "in process" while *later* lines have already started. In the example code below, you can imagine that the events might occur in this order, behind the scenes:
224+
225+
1. The new Promise object is constructed at Line 3, and the executor is passed on to it.
226+
2. The subscriber at Line 5 (the call to `alert`) is registered with the Promise.
227+
3. The executor is finally run by the Promise object and immediately resolves.
228+
4. The second `alert` call, at Line 7, is executed.
229+
6. The Promise notices that it has been resolved and therefore executes the registered call to `alert` from Line 5.
217230

218231
```js run
219-
// an immediately resolved promise
220-
let promise = new Promise(resolve => resolve("done!"));
232+
// an "immediately" resolved Promise
233+
const executor = resolve => resolve("done!");
234+
const promise = new Promise(executor);
221235

222-
promise.then(alert); // done! (right after the current code finishes)
236+
promise.then(alert); // this alert shows last
223237

224238
alert("code finished"); // this alert shows first
225239
```
226240

227-
So the code after `.then` always executes before the handler (even in the case of a pre-resolved promise). Usually that's unimportant, in some scenarios may matter.
241+
So the code *after* `.then` ends up always running *before* the Promise's subscribers, even in the case of an immediately-resolved Promise. Usually that's unimportant, in some scenarios it may matter a great deal.
228242
````
229243
230-
Now let's see more practical examples how promises can help us in writing asynchronous code.
244+
Now, let's see more practical examples of how promises can help us to write asynchronous code.
231245
232246
## Example: loadScript
233247
234248
We've got the `loadScript` function for loading a script from the previous chapter.
235249
236-
Here's the callback-based variant, just to remind it:
250+
Here's the callback-based variant, just to remind us of it:
237251
238252
```js
239253
function loadScript(src, callback) {
@@ -247,9 +261,9 @@ function loadScript(src, callback) {
247261
}
248262
```
249263
250-
Let's rewrite it using promises.
264+
Let's rewrite it using Promises.
251265
252-
The new function `loadScript` will not require a callback. Instead it will create and return a promise object that settles when the loading is complete. The outer code can add handlers to it using `.then`:
266+
The new function `loadScript` will not require a callback. Instead, it will create and return a Promise object that resolves when the loading is complete. The outer code can add handlers (subscribing functions) to it using `.then`:
253267
254268
```js run
255269
function loadScript(src) {
@@ -278,13 +292,13 @@ promise.then(
278292
promise.then(script => alert('One more handler to do something else!'));
279293
```
280294
281-
We can immediately see few benefits over the callback-based syntax:
295+
We can immediately see a few benefits over the callback-based pattern:
282296
283297
```compare minus="Callbacks" plus="Promises"
284298
- We must have a ready `callback` function when calling `loadScript`. In other words, we must know what to do with the result *before* `loadScript` is called.
285299
- There can be only one callback.
286-
+ Promises allow us to code things in the natural order. First we run `loadScript`, and `.then` write what to do with the result.
287-
+ We can call `.then` on a promise as many times as we want, at any time later.
300+
+ Promises allow us to do things in the natural order. First, we run `loadScript`, and `.then` we write what to do with the result.
301+
+ We can call `.then` on a Promise as many times as we want. Each time, we're adding a new "fan", a new subscribing function, to the "subscription list". More about this in the next section: [Promise Chaining](/promise-chaining).
288302
```
289303
290-
So promises already give us better code flow and flexibility. But there's more. We'll see that in the next chapters.
304+
So Promises already give us better code flow and flexibility. But there's more. We'll see that in the next chapters.

0 commit comments

Comments
 (0)