Created
February 23, 2018 22:44
-
-
Save v0lkan/124e4f221869ed8e6db069a514bb693d to your computer and use it in GitHub Desktop.
The evolution of a moderately-complicated fetch request
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
// 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