VanDalkvist
9/23/2015 - 3:40 PM

Micro Promise

Micro Promise

"use strict";

var module = {};

(function (module) {

    if (!!module.Promise) return;

    /**
     * @constructor
     */
    function Promise() {
        this._inner = {
            success: _noop,
            fail: _noop,
            finally: _noop,
            error: _noop
        };
    }

    Promise.prototype.then = _then;
    Promise.prototype.finally = _finally;
    Promise.prototype.catch = _catch;

    // static methods
    Promise.defer = function () {
        return new Defer();
    };

    function _then(success, fail) {
        var promise = this;

        promise._inner.success = success || _noop;
        promise._inner.fail = fail || _noop;

        return promise;
    }

    function _finally(fn) {
        var promise = this;

        promise._inner.finally = fn || _noop;
    }

    function _catch(fn) {
        var promise = this;

        promise._inner.error = fn || _noop;

        return promise;
    }

    module.Promise = Promise;

    /**
     * @constructor
     */
    function Defer() {
        this.promise = new Promise();
    }

    Defer.prototype.resolve = _resolve;
    Defer.prototype.reject = _reject;

    function _resolve(res) {
        var defer = this;

        _execute.call(defer, res, defer.promise._inner.success);
    }

    function _reject(rejected) {
        var defer = this;

        _execute.call(defer, rejected, defer.promise._inner.fail);
    }

    function _execute(result, fn) {
        var defer = this;
        try {
            fn(result);
        }
        catch (err) {
            defer.promise._inner.error(err);
        }
        finally {
            defer.promise._inner.finally();
        }
    }

    function _noop() {
    }

})(module);