Skip to content

Instantly share code, notes, and snippets.

@bouchtaoui-dev
Last active January 15, 2019 14:51
Show Gist options
  • Select an option

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

Select an option

Save bouchtaoui-dev/b1acf1d555a1b2c58624d916041b07e4 to your computer and use it in GitHub Desktop.
/**
* 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