Last active
January 15, 2019 12:35
-
-
Save bouchtaoui-dev/4d2ce3cac61db3bc0567f830ffd1c47a to your computer and use it in GitHub Desktop.
Simple example of a Promise pattern
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 | |
| * 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