Skip to content

Instantly share code, notes, and snippets.

@bouchtaoui-dev
Last active January 15, 2019 14:50
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 bouchtaoui-dev/793205f600278c52f85fdecf44607b62 to your computer and use it in GitHub Desktop.
Save bouchtaoui-dev/793205f600278c52f85fdecf44607b62 to your computer and use it in GitHub Desktop.
/**
* This function returns a promise to fetch a user by id
*/
function getUserWithId(id) {
return new Promise((resolve, reject) => {
// Look for a user with id in the database
User.find({_id: id}, (user, err) => {
if(err) return reject(err);
// on success
resolve(user); // from pending --> resolved
});
});
}
/**
* This function returns a promise to fetch a list of friends
*/
function getUserWithFriends(id) {
return new Promise((resolve, reject) => {
// Look for a user with id in the database
Friends.find({friends.id: id}, (friends, err) => {
if(err) return reject(err);
// on success
resolve(friends); // from pending --> resolved
}
});
}
function getUserImage(url) {
return new Promise((resolve, reject) => {
// Look for a user with id in the database
http.get({link: url}, (image, err) => {
if(err) return reject(err);
// on success pass the image
resolve(image);
});
});
}
/**
* No chaininig promises anymore, this looks much cleaner.
*/
async function performMultipleTasks(req, res, next) {
try {
// Now the method calls look like synchronous calls, which is more cleaner and easier to read
const user = await getUserWithId(req.params.id);
const friends = await getFriendsFromUser(user); // sorry for renaming this function
const image = await getUserImage(user.imageUrl);
return next();
} catch(err) {
// do something with the error
}
}
performMultipleTasks(req, res, next);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment