2017-07-17 65 views
0

我正在创建脚本以在页面上运行。这个页面有几个ajax调用,每个调用都是顺序的(如果A有效,调用B等)。XMLHttpRequest包装? (清理多个请求)

我的代码:

function doSomething(element) { 
    var xhr = new XMLHttpRequest(); 

xhr.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     pageCheck(this,element); 

    } 
} 


xhr.open('GET', URL); 
xhr.responseType = 'document'; 
xhr.send(); 
} 

里面pageCheck,我通过元素(不要紧,它是什么),并通过XMLHttpRequest调用获得的DOM对象。 Inside pageCheck我有另一系列的

pageCheck(page,item) { 
var xhr1 = new XMLHttpRequest(); 

xhr1.onreadystatechange = function() { 
if (...) { 
doSomethingElse(..); 
} 
xhr1.open(..) 
xhr1....etc 
} 

我的问题是,这看起来很可怕。我不能为XML请求做一些包装吗?我有这个,但意识到我不能访问xhr对象。我怎样才能清理这个没有抓取,jQuery的,承诺等?重新使用xhr对象?

function XMLWrapper(url) { 
    var xhr = new XMLHttpRequest(); 

    xhr.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     pageCheck(this,item); 

    } 
} 


    xhr.open('GET', url); 
    xhr.responseType = 'document'; 
    xhr.send();  
} 
+0

为什么downvotes?试图清理这件事,我知道它看起来很糟糕。 – Kevin

回答

0

我想诺言会救你在这里。虚拟代码:

function request (url) { 
    return new Promise(function (resolve, reject) { 
    var xhr = new XMLHttpRequest(); 

    //.... 
    //.... xhr setup 
    //.... 

    xhr.addEventListener('load', function (e) { 
     resolve(e.target.responseText) 
    }) 

    xhr.addEventListener('error', function (e) { 
     reject(new Error('some error message')); 
    }) 

    xhr.send(); 
    }) 
} 

比你可以:

request('url1') 
    .then(function (data) { 
    //data has the result of the first request here 

    return request('url2'); 
    }) 
    .then(function (data) { 
    //data has the result of the second here 

    }) 
    .catch(function (error) { 
    //if some error occurs on the way, 
    //you will end up here. 
    }) 

//and so forth 

请不认为这是伪代码,就在那里勾勒出一个可能与承诺解决你的问题的方式。关于承诺的完整解释将在这里得到很多答案。

+0

这可以用纯香草JS完成吗?或者我会不得不使用承诺这样的事情? – Kevin

+0

http://caniuse.com/#search=promises - 但那里有很好的polyfill,以防你需要针对没有承诺的浏览器。 – philipp