Skip to content

Instantly share code, notes, and snippets.

@Amosel
Created August 27, 2019 21:42
Show Gist options
  • Save Amosel/413a3562cd0e8bb707fa5fbf0f5bee77 to your computer and use it in GitHub Desktop.
Save Amosel/413a3562cd0e8bb707fa5fbf0f5bee77 to your computer and use it in GitHub Desktop.
hr.gs/mob-frontend
const { writeFile } = require('fs')
const fetchUsers = () =>
new Promise(r => {
setTimeout(() => {
r([
{
name: "amos",
id: "amos"
},
{
name: "soma",
id: "soma"
}
]);
}, 100);
});
const fetchPets = () =>
new Promise(r => {
setTimeout(() => {
r([
{
name: "geof",
userID: "amos"
},
{
name: "lyla",
userID: "soma"
}
]);
}, 100);
});
function workWithData() {
console.log("enter");
return Promise.all([fetchUsers(), fetchPets()])
.then(([users, pets]) => {
console.log(`users: ${users} pets: ${pets}`);
const petsByName = pets.sort((pet1, pet2) =>
pet1.name < pet2.name ? -1 : pet1.name > pet2.name ? 1 : 0
);
const userWithPets = users.map(user => ({
...user,
pets: pets.filter(({ userID }) => user.id === userID)
}));
return Promise.all([
writeFile("sorted-pets.json", JSON.stringify(petsByName), null, (err) => {
if(err) {
console.log('error' + err)
}
}),
writeFile("users-with-pets.json", JSON.stringify(userWithPets), null, (err) => {
if(err) {
console.log('error' + err)
}
})
]).catch(error => {
// handler special case here
});
})
.catch(error => {
console.log(`error ${error}`);
// handle network error
});
}
workWithData();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment