Last active
May 8, 2020 19:19
-
-
Save slmyers/5bfa1af903943d0b22e9189f5d287798 to your computer and use it in GitHub Desktop.
common promise mishaps
This file contains hidden or 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
// bad you're waiting for the first result but the second and third request don't need anything from the NAME query | |
// sequential async actions :do_not_want: | |
async fucntion waterfall(db) { | |
const name = await db.query(NAME) | |
const open = await db.query(IS_OPEN) | |
const welcomeMessage = await db.query(WELCOME_MESSAGE) | |
return { name, open, welcomeMessage } | |
} | |
// better there are no depenecies so start them all off at the same time | |
// concurrent :thinking_face: LGTM | |
async function concurrent(db) { | |
const [name, open, welcomeMessage] = await Promise.all([ | |
db.query(NAME), | |
db.query(IS_OPEN), | |
db.query(WELCOME_MESSAGE) | |
]) | |
return { name, open, welcomMessage } | |
} | |
// bad you don't need to await side effects that have no impact on execution flow, ie tracking | |
async function blockOnTracking(user, db) { | |
const record = await db.getSharedRecord(SHARED_RECORD) | |
await db.insertRowOnTrackingTable(user) | |
return record | |
} | |
// better, you can just fire off the action and return the data to the user more quickly | |
async function blockOnTracking(user, db) { | |
const record = await db.getSharedRecord(SHARED_RECORD) | |
// we need to handle the error or it might break your app potentially with an unhaldled promise rejection | |
db.insertRowOnTrackingTable(user).catch(handleError) | |
return record | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment