|
| 1 | +# promise and promise states |
| 2 | + |
| 3 | +## intro |
| 4 | + |
| 5 | +> in order to understand promises we must first understand why promises are |
| 6 | +> needed. When we run a program which relies on multiple events happening at |
| 7 | +> different times we have two options; we can either wait for each event to |
| 8 | +> conclude before moving to the next (synchronous), or we can launch multiple |
| 9 | +> events at the same time and set up protocols for how to interact with each |
| 10 | +> event, when and if they conclude(asynchronous). this is why we need promises. |
| 11 | +
|
| 12 | +## promises |
| 13 | + |
| 14 | +### description |
| 15 | + |
| 16 | +> promises are objects created to help us set protocols for the asynchronous |
| 17 | +> events described above. |
| 18 | +
|
| 19 | +- promises 'store' the event data set up by the program. |
| 20 | +- promises receive instructions set by the program on how to handle the event |
| 21 | + data at its various states. |
| 22 | + |
| 23 | +### promise states |
| 24 | + |
| 25 | +> let's say we created a promise for a fetch event where the program calls for |
| 26 | +> data from an external source. our promise might exist in one or more of three |
| 27 | +> states: |
| 28 | +
|
| 29 | +#### pending |
| 30 | + |
| 31 | +> a pending promise is a promise for an ongoing event; in the example above our |
| 32 | +> promise will be pending while the data from the external api hasn't been |
| 33 | +> received yet. |
| 34 | +
|
| 35 | +- the program must define a protocol for how to handle the data once it is |
| 36 | + received and/or rejected or the promise will remain pending forever. |
| 37 | + |
| 38 | +#### resolved |
| 39 | + |
| 40 | +> once the data has been received from the external source it can be handled by |
| 41 | +> the protocols set by the program. we can now say that the promise was |
| 42 | +> resolved. |
| 43 | +
|
| 44 | +- multiple protocols could be assigned to a single promise event on what is |
| 45 | + called a 'chain'. |
| 46 | + |
| 47 | +#### rejected |
| 48 | + |
| 49 | +> promises do not always resolve in a way that is compatible to the protocols we |
| 50 | +> have set up. for example; what if the external source does not have the data |
| 51 | +> the fetch event is looking for? in this case we can say the promise was |
| 52 | +> rejected, and our program should be able to handle unexpected or undesirable |
| 53 | +> outcomes without them breaking the rest of the code. |
| 54 | +
|
| 55 | +- reject protocols are set by the program to handle intentional promise outcomes |
| 56 | + that are incompatible with the resolve protocols. |
| 57 | +- reject protocols also handle any unintentional errors that may occur from the |
| 58 | + promise event. |
| 59 | + |
| 60 | +### references |
| 61 | + |
| 62 | +- for more information check out this |
| 63 | + [video](https://www.youtube.com/watch?v=QO4NXhWo_NM&t=4s) |
0 commit comments