Skip to content

Instantly share code, notes, and snippets.

@kikill95
Last active March 15, 2023 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kikill95/3dbe747d34f0a277c006 to your computer and use it in GitHub Desktop.
Save kikill95/3dbe747d34f0a277c006 to your computer and use it in GitHub Desktop.
Promises
// create Promise
var promise = new Promise(function(fulfill, reject) {
if (/* condition */) { // for example, statusCode === 200 or something else, whatever
fulfill(/* success params */);
} else {
reject(/* fail params */);
}
});
// work with Promise
promise.then(function(resolve) {
// do something if success
}).catch(function(rejected) {
// do something if fail
});
/*
First function is for success handler, second - for fail.
Also, we can chain promises like this:
*/
// ExampleA
promise.then(function(resolve) {
// successHandler1();
}).catch(function(rejected) {
// failHandler1();
}).then(function(resolve) {
// successHandler2();
}).catch(function(rejected) {
// failHandler2();
}).then(/* etc... */);
/*
You can just ignore failHandler1 (if you need) - so the failHandler2 will get the rejected parameter from the first 'then'.
ExampleA can be in the short form as ExampleB.
*/
// ExampleB (first paramater in success / fail Handlers will be resolved / rejected)
promise
.then(successHandler1).catch(failHandler1)
.then(successHandler2).catch(failHandler2)
.then(/* etc... */);
// ExampleC: only one failHandler (that will handle all errors), without big amount of failHandlers
promise
.then(successHandler1)
.then(successHandler2)
.then(/* etc... */)
.catch(failHandler);
promise.catch(onRejected); // only if error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment