Created
January 15, 2019 13:15
-
-
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 file contains hidden or 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); | |
| }); | |
| }); | |
| } | |
| /** | |
| * 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