0

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;
}
Sri
  • 1,205
  • 2
  • 21
  • 52
  • 2
    Theres an error in the first line of your question ;) – Jonas Wilms Dec 07 '17 at 20:29
  • Uh, that's just a horrible "promise" implementation, which does not allow us to tell where the error comes from. Why not use a proper Promise library/polyfill and [proper XHR promisification](https://stackoverflow.com/q/30008114/1048572)? There are so many problems in your code I don't even know where to start. – Bergi Dec 07 '17 at 23:13
  • Above code is from adobe aem csrf.js , aem application that i am working failing ajax calls intermittently by above code. – Sri Dec 08 '17 at 22:30

0 Answers0