Last active
February 23, 2017 08:29
-
-
Save TCotton/899781263068413107a9feefa935dd5f to your computer and use it in GitHub Desktop.
promise patterns and anti-promise patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://blog.runnable.com/post/154695425511/promise-anti-patterns | |
// BAD!! variable nesting | |
// Defining a variable to store later | |
var user | |
var accountInfo | |
fetchUser() | |
.then((fetchedUser) => { | |
// Setting the variable that we will use later | |
user = fetchedUser | |
}) | |
.then(() => { | |
return fetchAccountInfo(user) | |
}) | |
.then((fetchedAccountInfo) => { | |
accountInfo = fetchedAccountInfo | |
}) | |
.then(() => { | |
// Using the variables that have been set previously | |
return { | |
user: user, | |
accountInfo: accountInfo | |
} | |
}) | |
// ALTERNATIVE GOOD VERSION | |
var userFetchPromise = fetchUser() | |
var accountInfoFetchPromise = userFetchPromise | |
.then((user) => { | |
return fetchAccountInfo(user) | |
}) | |
return Promise.all([userFetchPromise, accountInfoFetchPromise]) | |
.then((results) => { | |
return { | |
user: results[0], | |
accountInfo: results[1] | |
} | |
}) | |
// ---------------------- | |
// Creating new promises -> BAD!!! | |
new Promise((resolve, reject) => { | |
fetchUser().then(resolve).catch(reject) | |
}) | |
.then((user) => { | |
// Do something with user | |
}) | |
// creating new promises -> GOOD!! | |
fetchUser() | |
.then((user) => { | |
// Do something with user | |
}) | |
// ---------------------- | |
// GOOD -> add errors | |
var fetchUser = (userId) => { | |
return Promise.resolve() | |
.then(() => { | |
if (!userId) { | |
throw new Error('User ID required') | |
} | |
return goFetchUser(userId) | |
}) | |
} | |
// Concurrency -> BAD!! | |
createDatabase() | |
.then(() => { | |
return insertUser() | |
}) | |
.then(() => { | |
return insertOrganization() | |
}) | |
// Concurrency -> GOOD! | |
createDatabase() | |
.then(() => { | |
return Promise.all([insertUser(), insertOrganization()]) | |
}) | |
// Anonymous Functions -> BAD!! | |
var userFetchPromise = fetchUser() | |
return Promise.props({ | |
user: userFetchPromise, | |
accountInfo: userFetchPromise.then((user) => { | |
return fetchAccountInfo(user) | |
}) | |
}) | |
// Remove anonymous functions | |
var userFetchPromise = fetchUser() | |
return Promise.props({ | |
user: userFetchPromise, | |
accountInfo: userFetchPromise.then(fetchAccountInfo) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment