|
1 | 1 | # About
|
2 | 2 |
|
3 |
| -TODO: add information on promises concept |
| 3 | +The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. |
| 4 | + |
| 5 | +A Promise is in one of these states: |
| 6 | + |
| 7 | +- **pending**: initial state, neither fulfilled nor rejected. |
| 8 | +- **fulfilled**: meaning that the operation was completed successfully and the result is available. |
| 9 | +- **rejected**: meaning that the operation failed. |
| 10 | + |
| 11 | +When either of these options happens, the associated handlers queued up by a promise's `then` method is called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. |
| 12 | + |
| 13 | +Example: |
| 14 | + |
| 15 | +```javascript |
| 16 | +const myPromise = new Promise(function (resolve, reject) { |
| 17 | + setTimeout(function (resolve, reject) { |
| 18 | + resolve('Jack'); |
| 19 | + }, 300); |
| 20 | +}); |
| 21 | +myPromise.then(function (e) { |
| 22 | + console.log(e); // expected output 'Jack' |
| 23 | +}); |
| 24 | +``` |
| 25 | + |
| 26 | +## Instance Methods of a Promise |
| 27 | + |
| 28 | +### then |
| 29 | + |
| 30 | +> The `.then()` method takes up to two arguments; the first argument is a callback function for the resolved case of the promise, and the second argument is a callback function for the rejected case. Each `.then()` returns a newly generated promise object, which can optionally be used for chaining.[^1] |
| 31 | +
|
| 32 | +```javascript |
| 33 | +const promise1 = new Promise(function (resolve, reject) { |
| 34 | + resolve('Success!'); |
| 35 | +}); |
| 36 | +promise1.then(function (value) { |
| 37 | + console.log(value); |
| 38 | + // expected output: "Success!" |
| 39 | +}); |
| 40 | +``` |
| 41 | + |
| 42 | +### catch |
| 43 | + |
| 44 | +> A `.catch()` is really just a `.then()` without a slot for a callback function for the case when the promise is resolved. It is used to handle rejected promises.[^2] |
| 45 | +
|
| 46 | +```javascript |
| 47 | +const promise1 = new Promise((resolve, reject) => { |
| 48 | + throw 'An error occured'; |
| 49 | +}); |
| 50 | +promise1.catch(function (error) { |
| 51 | + console.error(error); |
| 52 | +}); |
| 53 | +// expected output: An error occured |
| 54 | +``` |
| 55 | + |
| 56 | +### finally |
| 57 | + |
| 58 | +> When the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with.[^3] |
| 59 | +
|
| 60 | +```javascript |
| 61 | +function findDataById(id) { |
| 62 | + return new Promise(function (resolve, reject) { |
| 63 | + let sampleData = [1, 2, 3, 4, 5]; |
| 64 | + if (sampleData[id]) { |
| 65 | + resolve(sampleData[id]); |
| 66 | + } else { |
| 67 | + reject(new Error('Invalid id')); |
| 68 | + } |
| 69 | + }); |
| 70 | +} |
| 71 | +findDataById(4) |
| 72 | + .then(function (response) { |
| 73 | + console.log(response); |
| 74 | + }) |
| 75 | + .catch(function (err) { |
| 76 | + console.error(err); |
| 77 | + }) |
| 78 | + .finally(function () { |
| 79 | + console.log('Promise completed'); |
| 80 | + }); |
| 81 | +``` |
| 82 | + |
| 83 | +## Static Methods of the Promise Class |
| 84 | + |
| 85 | +Some of the [staic methods][promise-static-methods] that are available on `Promise` can be used resolve and reject promises. Here are a few of them: |
| 86 | + |
| 87 | +### Promise.all |
| 88 | + |
| 89 | +> The `Promise.all()` method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.[^4] |
| 90 | +
|
| 91 | +```javascript |
| 92 | +var p1 = Promise.resolve(10); |
| 93 | +var p2 = 45; |
| 94 | +var p3 = new Promise(function (resolve, reject) { |
| 95 | + setTimeout(function () { |
| 96 | + resolve('Jill'); |
| 97 | + }, 300); |
| 98 | +}); |
| 99 | +Promise.all([p1, p2, p3]).then(function (values) { |
| 100 | + console.log(values); // => [10, 45, "Jill"] |
| 101 | +}); |
| 102 | +``` |
| 103 | + |
| 104 | +### Promise.reject |
| 105 | + |
| 106 | +> The `Promise.reject()` method returns a Promise object that is rejected with a given reason.[^5] |
| 107 | +
|
| 108 | +```javascript |
| 109 | +Promise.reject(new Error('failed')).then( |
| 110 | + function () { |
| 111 | + // not called |
| 112 | + }, |
| 113 | + function (error) { |
| 114 | + console.error(error); // error in the console |
| 115 | + } |
| 116 | +); |
| 117 | +``` |
| 118 | + |
| 119 | +### Promise.resolve |
| 120 | + |
| 121 | +> The `Promise.resolve()` method returns a Promise object that is resolved with a given value. If the value is a promise, that promise is returned; if the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.[^6] |
| 122 | +
|
| 123 | +```javascript |
| 124 | +Promise.resolve('resolved!').then( |
| 125 | + function (value) { |
| 126 | + console.log(value); // "resolved!" |
| 127 | + }, |
| 128 | + function (value) { |
| 129 | + // not called |
| 130 | + } |
| 131 | +); |
| 132 | +``` |
| 133 | + |
| 134 | +--- |
| 135 | + |
| 136 | +[^4]: `all`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all |
| 137 | +[^5]: `reject`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject |
| 138 | +[^6]: `resolve`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve |
| 139 | +[^1]: `then`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then |
| 140 | +[^2]: `catch`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch |
| 141 | +[^3]: `finally`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally |
| 142 | + |
| 143 | +[promise-catch]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch |
| 144 | +[promise-then]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then |
| 145 | +[promise-finally]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally |
| 146 | +[promise-static-methods]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#static_methods |
0 commit comments