Jump to content

XMLHttpRequest Order Shuffled


beennn

Recommended Posts

I am trying to fetch some images from a server, however I need them to come back in the order requested. Currently, the below returns the images back in a seemingly random order, I guess which ever are finished first. How can I ensure I get the images back in the order they were requested?

var xhr = [];for (i = 0; i < count; i++){	(function (i){			xhr[i] = new XMLHttpRequest();		xhr[i].open( "GET", url + dir + "/" + i.toString() + ".png", true );		xhr[i].responseType = "arraybuffer";				xhr[i].onreadystatechange = function () {							if (xhr[i].readyState == 4 && xhr[i].status == 200) {							var arrayBufferView = new Uint8Array( xhr[i].response );				var blob = new Blob( [ arrayBufferView ], { type: "image/png" } );							console.log("xhr: " + i + ".png");							}					};				xhr[i].send();			})(i);	}
I want it to always output:
xhr: 0.png
xhr: 1.png
xhr: 2.png

I currently get a mixture of, and including the above:

xhr: 0.png
xhr: 2.png
xhr: 1.png
Or:
xhr: 1.png
xhr: 2.png
xhr: 0.png

 

Link to comment
Share on other sites

Thanks, wasn't the answer I was hoping for, but it got me on the right track.

 

I ended up adding the responses to an array; when I had all the responses back, I sorted the array from 0 upwards and that fixed me problem. Alternatively, if I didn't need to set responseType, I could have just set async to false.

Link to comment
Share on other sites

The results in the example above are stored in the array in the order that the response is received, not in the order that the requests are sent. So in the original post, where xhr[0] should equal 0.png, it's possible that 1.png is received before 0.png and so that is stored in xhr[0] instead.

Edited by beennn
Link to comment
Share on other sites

It doesn't seem like the order would matter, since you have the array index that you can use to put each image at the position where you want it. Other than that, to answer your original question, you would need to chain the requests so that you only send another request when one finishes.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...