Skip to content

Instantly share code, notes, and snippets.

@bouchtaoui-dev
Created January 15, 2019 13:15
Show Gist options
  • Select an option

  • Save bouchtaoui-dev/fb16bfeb47ffbbc5c0a9f0f5c06cc5b0 to your computer and use it in GitHub Desktop.

Select an option

Save bouchtaoui-dev/fb16bfeb47ffbbc5c0a9f0f5c06cc5b0 to your computer and use it in GitHub Desktop.
Here we're chaining multiple promises, which solves the callback hell.
/**
* 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);
});
});
}
/**
* Chaininig promises :)
*/
getUserWithId(someId)
.then(user => getUserWithFriends)
.then(friends => getUserImage(url))
.then(image)
.catch(ex => {
// send or throw an error
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment