Reputation: 139
I'm creating a script to run on a page. This page has a few ajax calls, each of them being sequential (if A works, make call B, etc).
My code:
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();
}
Inside pageCheck, I pass element (doesn't matter what it is) and the dom object obtained through that xmlhttprequest call. Inside pageCheck I have another series of
pageCheck(page,item) {
var xhr1 = new XMLHttpRequest();
xhr1.onreadystatechange = function() {
if (...) {
doSomethingElse(..);
}
xhr1.open(..)
xhr1....etc
}
My issue is, this looks horrible. Can't I make some wrapper for the XML requests? I had this, but realized I can't access the xhr object. How can I clean this up without fetch, jquery, promises, etc? Re-use the xhr object?
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();
}
Upvotes: 1
Views: 1443
Reputation: 16495
I guess Promises will save you here. Dummy code:
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();
})
}
Than you can:
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
Please not that this is dummy code, just there to outline the way one might solve your problem with promises. A full explanation on Promises would be to much for an answer here.
Upvotes: 2