Permalink
Browse files

Adds Rules of Using Promises

Pulled these in from slack -- not an issue:
https://ga-students.slack.com/archives/G3NTE79M4/p1494262598158412
  • Loading branch information...
payne-chris-r
payne-chris-r committed May 8, 2017
1 parent 7b10a13 commit 8b74380a282ee5bde63aa84a9916ee22cb98bea6
Showing with 62 additions and 0 deletions.
  1. +48 −0 README.md
  2. +3 −0 snippets/callback-vs-invocation.js
  3. +3 −0 snippets/format.js
  4. +8 −0 snippets/nesting.js
@@ -142,6 +142,54 @@ readJSON('./example.json')
```
<!-- end code block -->

### Rules for Promisifying Your Code:
1. Only ever pass a function as a call back. NEVER pass a function invocation!
<details>
<summary>*Why?*</summary>
The difference is `.then()` _expects_ a callback. If you invoke the function, the `.then` gets a _value_ NOT a function to invoke later.
</details>
<!-- start code block file="snippets/callback-vs-invocation.js" -->
```js
.then(JSON.parse)
// vs
.then(JSON.parse(json))
```
<!-- end code block -->
1. ALWAYS consider WHAT is being return from each block of a promise chain. Be explicit if you need to!
<details>
<summary>*Why?*</summary>
Because some methods don't return what you expect them to. If you're ever unsure, BE SURE by making it explicit!
</details>
1. Safety third <details>
<summary>*Why?*</summary>
'cause it should never be first or second.
</details>
1. Indent once at the start, and then lineup your `.then`s and `.catch`s <details>
<summary>*Why?*</summary>
Because formatting is important to humans.
</details>
<!-- start code block file="snippets/format.js" -->
```js
startingFunction()
.then(JSON.parse)
.catch(console.error)
```
<!-- end code block -->
1. Never nest `.then`s--return out, and continue with the next `.then` in-line. *Why?* Because nesting `.then`s defeats the purpose of promises.
<!-- start code block file="snippets/nesting.js" -->
```js
startingFunction()
.then(JSON.parse)
.then((pojo) => {
functionThatReturnsAPromise(pojo)
.then(dontDoThis!) // <-- creates promise hell!
})
.then(doThisInstead!) // <-- narrowly avoids promise hell!
.catch(console.error)
```
<!-- end code block -->


### Code-Along: Promisify `copy-json.js`

### Lab: Promisify `hey-yall.js`
@@ -0,0 +1,3 @@
.then(JSON.parse)
// vs
.then(JSON.parse(json))
@@ -0,0 +1,3 @@
startingFunction()
.then(JSON.parse)
.catch(console.error)
@@ -0,0 +1,8 @@
startingFunction()
.then(JSON.parse)
.then((pojo) => {
functionThatReturnsAPromise(pojo)
.then(dontDoThis!) // <-- creates promise hell!
})
.then(doThisInstead!) // <-- narrowly avoids promise hell!
.catch(console.error)

0 comments on commit 8b74380

Please sign in to comment.