Promises promises

Just for fun, my own promises implementation.

by Richard Hunter

JavaScript

function Promise(init) {
    
    this.state = {
        pending : true,
        fulfilled : false,
        rejected : false,
        value : null,
        reason : null    
    }
    
    function reject(reason) {
        this.state.reason = reason;
        this.state.rejected = true;
        this.state.pending = false;    
    }

    if(init) {
        init(this.fulfil.bind(this), this.reject.bind(this));
    }
}


Promise.prototype.fulfil = function (value) {

    this.state.pending = false;
    this.state.fulfilled = true;
    this.state.value = value;
}

Promise.prototype.reject = function () {
    this.state.reason = reason;
    this.state.rejected = true;
    this.state.pending = false;  
}

Promise.prototype.then = function (fulfilled, rejected) {
    var count = 0;
    var self = this;
    //  promise to be returned by this function
    var promise2 = new Promise();
    
    (function pending() {
        
        if(!self.state.pending) {
            if(self.state.fulfilled) {
                var x = fulfilled(self.state.value);
                if(x instanceof Promise) {  
                    //  if x is a Promise, set the state of promise2 to be that of x
                    promise2.state = x.state;
                } else {
                    //  else fulfil promise2 with x
                    promise2.fulfil(x);
                }
                console.log("fulfilled");
            } else if(self.state.rejected) {
                rejected(self.state.reason);
                console.log("rejected");
            }    
        } else {
            if(count < 10) {
                count++;
                console.log("pending");
                window.setTimeout(pending, 100);
            } else {
                console.log("timeout");
            }
        }
    })();
    
    return promise2;
}

var promise = new Promise(function(fulfil, reject){
    setTimeout(fulfil, 100, "apple");

});

promise.then(function (arg) {

    console.log("success",...