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;
}