Skip to content

Instantly share code, notes, and snippets.

@hitrik
Last active March 15, 2018 10:28
Show Gist options
  • Save hitrik/a7c5f2702d8b66488354a3835d5fb46c to your computer and use it in GitHub Desktop.
Save hitrik/a7c5f2702d8b66488354a3835d5fb46c to your computer and use it in GitHub Desktop.
some experience with compose
//compose
const compose = (...fns) => arg =>
fns.reduce((composed, fn) => fn(composed), arg);
//fetch all urls
const fetchUrls = urls => urls.map(url => fetch(url));
//parse body like json
const parseResponses = responses =>
responses.map(response => response.then(data => data.json()));
//resolve array of promises
const resolveAllResults = arr => Promise.all(arr);
//convert to string
const stringify = arr => arr.then(data => data.map(d => JSON.stringify(d)));
//just output for example
function output(arr) {
const root = document.querySelector("#root");
arr.forEach(a => root.innerHTML += a);
return arr;
}
//implementation
compose(fetchUrls, parseResponses, resolveAllResults, stringify)([
"https://jsonplaceholder.typicode.com/users",
"https://jsonplaceholder.typicode.com/posts/1",
"https://jsonplaceholder.typicode.com/posts/2"
])
.then(output)
.then(console.log, error => console.log("¯\_(ツ)_/¯"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment