var Promiseme = function () {
var promState = {
pending: 1,
fulfilled: 2,
rejected: 3
};
//check the enumeration of promise states
var Promiseme = {
//set default state
myState: promState.pending,
changeMyState: function (newState, newValue) {
// check 1: if we are changing to same state and report it
if (this.myState == newState) {
throw new Error("Sorry, But you can't do this to me! You are transitioning to same state: " + newState);
}
// check2: trying to get out of the fulfilled or rejected states
if (this.myState == promState.fulfilled || this.myState == promState.rejected) {
throw new Error("You can't leave this state now: " + this.myState);
}
// check 3: if promise is rejected with a null reason
if (newState == promState.rejected && newValue === null) {
throw new Error("If you get rejected there must be a reason. It can't be null!");
}
//check: 4 if there was no value passed with fulfilled
if (newState == promState.fulfilled && arguments.length < 2) {
throw new Error("I am sorry but you must have a non-null value to proceed to fulfilled!");
}
// we passed all the conditions, we can now change the state
this.myState = newState;
this.value = newValue;
this.resolve();
return this.myState;
},
fulfillPromise: function (value) {
this.changeMyState(promState.fulfilled, value);
},
rejectPromise: function (reason) {
this.changeMyState(promState.rejected, reason);
},
then: function (onFulfilled, onRejected) {
// define an array named handlers
this.handlers = this.handlers || [];
// create a promise object
var...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.