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