Skip to content

Instantly share code, notes, and snippets.

@v0lkan
Created February 23, 2018 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save v0lkan/124e4f221869ed8e6db069a514bb693d to your computer and use it in GitHub Desktop.
Save v0lkan/124e4f221869ed8e6db069a514bb693d to your computer and use it in GitHub Desktop.
The evolution of a moderately-complicated fetch request
// Assume `fetch` and `notify` are defined elsewhere.
// ## 1. CPS With Nodebacks
function fetchAppState() {
return function(dispatch) {
fetch(function(err, data) {
if (err) {
console.error('Poop', err);
return;
}
dispatch(data);
});
}
}
// ## 2. ES6ification
const fetchAppState = () => (dispatch) =>
fetch((err, data) => {
if (err) {
console.error('Poop', err);
return;
}
dispatch(data);
});
// ## 3. Promisified fetch
const fetchAppState = () => (dispatch) =>
fetch()
then(dispatch)
catch((err) => {
console.error('Poop', err);
});
// ## 4. Flatten code further with async/await
const fetchAppState = () => (dispatch) => {
try {
dispatch(await fetch());
} catch (poop) {
console.error('Poop', poop);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment