Last active
January 15, 2019 14:50
-
-
Save bouchtaoui-dev/793205f600278c52f85fdecf44607b62 to your computer and use it in GitHub Desktop.
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
/** | |
* 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