Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save bouchtaoui-dev/4d2ce3cac61db3bc0567f830ffd1c47a to your computer and use it in GitHub Desktop.
Simple example of a Promise pattern
/**
* promise object
* Explanation: When creating a promise object, it is supposed to be in a pending state.
* If a certain process succeeded, we call resolve() callback and it is assumed resolved,
* also called fulfilled. Meaning, you fulfilled your promise :)
* If the process failed, than the promise is rejected.
*/
let promise = new Promise((resolve, reject) => {
// We're now in a pending state
User.find({}, (user, err) => { // <-- this an async work
// on failure (from pending --> rejected)
if(err) return reject(new Error('error message');
// on success
resolve(user); // from pending --> resolved
}
});
/**
*
*/
promise.then(user => {
// we got a successfull object, send it back to the user or
// something like that.
})
.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