2017-07-17 28 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