Home Invalid state error on promise.resolve
Reply: 0

Invalid state error on promise.resolve

Sri
1#
Sri Published in 2017-12-07 20:27:23Z

Browser: IE

I have below code, which throws invalid state error and executes promise.reject in exception catch block.

Invalid state exception not thrown all the time, why?

globalToken below is undefined and promise.resolve(globalToken); throws invalid state error intermittently.

how to make sure , xhr request always go through irrespective of promise resolve or reject

Promise.prototype = {
    then: function (resolveFn, rejectFn) {
        this._handler.push({resolve: resolveFn, reject: rejectFn});
    },
    resolve: function () {
        this._execute('resolve', arguments);
    },
    reject: function () {
        this._execute('reject', arguments);
    },
    _execute: function (result, args) {
        if (this._handler === null) {
            throw new Error('Promise already completed.');
        }

        for (var i = 0, ln = this._handler.length; i < ln; i++) {
            this._handler[i][result].apply(window, args);
        }

        this.then = function (resolveFn, rejectFn) {
            (result === 'resolve' ? resolveFn : rejectFn).apply(window, args);
        };

        this._handler = null;
    }

};

var promise, globalToken;

function getToken() {
    promise = new Promise();

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            try {
                var data = JSON.parse(xhr.responseText);
                globalToken = data.token;
                promise.resolve(globalToken);
            } catch (ex) {
                promise.reject(xhr.responseText);
            }
        }
    };
    xhr.open('GET', Granite.HTTP.externalize(TOKEN_SERVLET), true);
    xhr.send();

    return promise;
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.326559 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO