Last active
January 15, 2019 14:51
-
-
Save bouchtaoui-dev/b1acf1d555a1b2c58624d916041b07e4 to your computer and use it in GitHub Desktop.
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
| /** | |
| * promise object | |
| */ | |
| 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 is a async method, which is awaiting on getUserWithId call in another thread. | |
| * The async/await is actually a syntaxical sugar, which means, it does the same as | |
| * Promise, but its syntax is cleaner and looks like a synchronous call. | |
| */ | |
| async function findUser(req, res) { | |
| try { // to handle also a catch, we put this in a try/catch clausule | |
| // --- begins a separate thread | |
| const user = await getUserWithId(req.params.id); | |
| // --- ends the thread with a result. | |
| res.send(user); | |
| } catch(err) { | |
| // do something with the error | |
| } | |
| } | |
| /** | |
| * Now call async function, this function will return immediately, | |
| * after kicking off a new thread to run the getUserwithId() function. | |
| */ | |
| findUser(req, res); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment