I wrote a basic promise just to fill the promises better. If anyone wants an exercise, please fill free to add
Promize.prototype.all and Promize.prototype.race

//just added custombind function, just because I can. Normally I would use js, bind function
function custombind(newthis) {
    return ()=>{ this.apply(newthis, arguments)};
}
Function.prototype.custombind = custombind;

function Promize(control) {
    let states = {
        p: 'pending',
        f: 'fulfilled',
        r: 'rejected'
    };
    //default state is pending
    this.state = states.p;
    let successes = [];
    let catches = [];

    this.then = function (callback) {
        successes.push(callback);
        return this;
    };

    this.catch = function (callback) {
        catches.push(callback);
        return this;
    };

    this.resolve = function (value) {
        if (this.state === states.p) {
            this.state = states.f;
            successes.forEach(function (successCallback, key, arr) {
                successCallback(value);
            });
        }
    };

    this.reject = function (reason) {
        if (this.state === states.p) {
            this.state = states.r;
            catches.forEach(function (rejectCallback, key, arr) {
                rejectCallback(reason);
            });
        }
    };

    control(this.resolve.custombind(this), this.reject.custombind(this));
}

//example of usage
let prom = new Promize(function (resolve, reject) {
    setTimeout(function () {
        resolve();
    }, 5000);
});
prom.then(function () {
    alert('resolved!');
});
prom.then(function () {
    alert(prom.state);
});

Leave a Reply

Your email address will not be published. Required fields are marked *