Last active
October 13, 2017 02:57
-
-
Save jasonrhodes/af4e825103593a863ed529f66b7461f2 to your computer and use it in GitHub Desktop.
the trouble with redux async chaining
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
import asyncDispatcher from './asyncDispatcher' | |
export function updateThing1(options) { | |
return asyncDispatcher('UPDATE_THING_1', options); | |
} | |
export function updateThing2(options) { | |
return asyncDispatcher('UPDATE_THING_2', options); | |
} | |
export function updateSequence(thing_1_options) { | |
return (dispatch) => dispatch(updateThing1(thing_1_options)) | |
.then((results) => dispatch(updateThing2(results)) | |
} |
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
export default function asyncDispatcher(baseType, options) { | |
return (dispatch) => { | |
dispatch({ type: `${baseType}_PENDING` }) | |
return doAsyncThing(options) | |
.then((results) => { | |
dispatch({ type: `${baseType}_SUCCESS`, payload: results }) | |
}) | |
.catch((err) => { | |
dispatch({ type: `${baseType}_FAIL`, payload: err }) | |
// QUESTION: TO THROW OR NOT TO THROW? | |
// throw err | |
}) | |
} | |
} |
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
class ChainingAsync extends React.Component { | |
componentWillReceiveProps(newProps) { | |
// handle changes in connected props to do things | |
// like show alerts, redirect, etc. | |
} | |
updateThings(values) { | |
this.props.updateSequence(values) | |
// ^^ HERE, ASSUME updateThing1 FAILED... | |
// if the asyncDispatcher DOES NOT throw on fail: | |
// we would've went on to updateThing2 with an undefined results value | |
// because we swallowed the error from updateThing1 | |
// if the asyncDispatcher DOES throw on fail: | |
// we now HAVE to add a .catch() here, for no real reason, like so: | |
.catch(() => { | |
// do nothing | |
}) | |
// otherwise we get Unhandled promise rejection errors anytime | |
// any of those async actions fail | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A possible solution?
asyncDispatcher
becomes:Then a 'series' helper:
Then the actions
Now if
updateThing1
fails, you'd have two actions:No .catch() needed anywhere