浏览器:IE
我有下面的代码,它会抛出无效的状态错误并在异常catch块中执行promise.reject。
无效状态异常不会一直抛出,为什么?
下面的globalToken是undefined和promise.resolve(globalToken);间歇性地抛出无效状态错误。
如何确保,xhr请求始终通过,无论承诺解决或拒绝
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;
}