Promise化

function Request() {
    this.req = new XMLHttpRequest();
}
Request.prototype = {
    get : function(url, timeout) {
        var req = this.req;
        return new Promise(function(resolve, reject) {
            req.open('GET', url, true);
            req.timeout = timeout || 0;
            req.responseType = 'document';
            req.onload = function() {
                if (req.status == 200) resolve(req.response);
                else reject(new Error(req.status + " " + req.statusText));
            };
            req.onerror = function() {
                reject(new Error('Network Error'));
            };
            req.ontimeout = function(){
                reject(new Error('Timeout'));
            };
            req.onabort = function() {
                reject(new Error('User Cancel'));
            };
            req.send(null);
        });
    },
    abort : function() {
        if (this.req.readyState != 4) this.req.abort();
    },
}; 

メモ

MDN見ても古い情報と新しい情報が混在してるのでメモ

タグ:

+ タグ編集
  • タグ:
最終更新:2014年11月23日 11:24