41 | | == New class skeleton |
| 43 | == Understanding and Using Promises |
| 44 | |
| 45 | [http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/ What's so great about Promises?] [http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/ The point of promises is to give us back functional composition] and error bubbling in the async world. They do this by saying that your functions should return a promise, which can do one of two things: |
| 46 | |
| 47 | Become __fulfilled__ by a **value** |
| 48 | Become __rejected__ with an **exception** |
| 49 | |
| 50 | And, if you have a correctly implemented `then()` function, then fulfillment and rejection will compose just like their synchronous counterparts, with fulfillments flowing up a compositional chain, but being interrupted at any time by a rejection that is only handled by someone who declares they are ready to handle it. |
| 51 | |
| 52 | === Promise Gotchas |
| 53 | |
| 54 | (Summarized from [http://making.change.org/post/69613524472/promises-and-error-handling change.org Blog] and [http://taoofcode.net/promise-anti-patterns/ The Art of Code Blog]) |
| 55 | |
| 56 | * Don't nest promises to perform multiple async operations; instead, chain them or use `Promise.all()`. |
| 57 | * Beware of storing or returning promise values that are not from the end of a chain. Each `.then()` returns a new promise value, so return the last promise. |
| 58 | * Use `Promise.all()` with `map()` to process an array of asynchronous work in parallel. Use `Promise.all()` with `reduce()` to sequence an array asynchronous work. |
| 59 | * If a result may be a promise or an actual value, wrap the value in a promise, e.g., `Promise.resolve(val)` |
| 60 | * Use `.catch()` at the end of a chain to perform error handling. |
| 61 | * To reject a promise, throw an `Error` instance or call the `reject` callback with an `Error` instance. |
| 62 | * A `.catch()` block is considered resolved if it does not re-throw an Error instance. Re-throw if you want to log an error message and allow other parts of a chain (i.e, an API client) to handle an error condition. |
| 63 | * Don't directly pass a promise's `resolve` function to Object.addEventListener, as it will leak the promise. Instead, use a single-fire WebInspector.EventListener object defined outside of the promise chain and connect it inside a `.then()` body. Inside the `.catch` block, disconnect the EventListener if necessary. |
| 64 | |
| 65 | == New class skeleton |