Skip to content

Instantly share code, notes, and snippets.

@v0lkan
Last active February 26, 2018 08:27
Show Gist options
  • Save v0lkan/9f696df79bc0ea4a434b5f85d4573dec to your computer and use it in GitHub Desktop.
Save v0lkan/9f696df79bc0ea4a434b5f85d4573dec to your computer and use it in GitHub Desktop.
The Evolution of a Fetch
// Assume `dispatch` and `fetchFromNetwork` are defined elsewhere.
// ## 1. CPS With Nodebacks
// This is the old-school-style fetch. Mostly here for
// historical reasons.
//
// Yet, contrary to the arguments against using it,
// it‘s not that hard to maintain this code when you are
// careful and know what you are doing.
//
// For starters, you can extract the `function(err, data)`
// below to its own function and flatten th nested callback
// structure.
function fetchAppState() {
fetchFromNetwork(function(err, data) {
if (err) {
console.error('Poop', err);
return;
}
dispatch(data);
});
}
// ## 2. ES6ification
// Look ma! No more `function` keywords.
// Does the same thing; and mostly syntactic sugar.
// This is a step in the right direction.
const fetchAppState = () => fetchFromNetwork((err, data) => {
if (err) {
console.error('Poop', err);
return;
}
dispatch(data);
});
// ## 3. Promisified `fetchFromNetwork`
// Although using Promises gives a compacter look,
// you still need to understand how Promises work
// to follow through the code and avoid common pitfalls.
//
// Promises are Monadic structures, and it can require some
// getting used to, especially if you haven’t used a similar
// paradigm before.
//
// That said, prefer Promises to continuation-passing-style code
// (that you see above in examples 1 and 2) whenever you can.
const fetchAppState = () => fetchFromNetwork()
.then(dispatch)
.catch((err) => console.error('Poop', err));
// ## 4. Flatten code further with async/await
// Although the code works identically, it’s flatter.
// It’s (arguably) the most readable of all.
//
// If you are running this code in a browser, you
// might need to polyfill it with Regenerator-Runtime.
// Though, everybody is using Babel or one of its variants anyway.
// So it should not be that big of a deal.
async function fetchAppState() {
try {
const data = await fetchFromNetwork();
dispatch(data);
} catch (poop) {
console.error('Poop', poop);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment