How to async a synchronous loop

So I am currently tasked with converting some code to load XML asynchronously that is currently coded to load it synchronously.  Today I had to tackle the problem of, what happens when you want to load XML inside a loop, and then process the loaded XML outside of the loop.  So you have something like this:-

for (var i = 0; i < items.length; i++) {
  items[i].xml = synchronousLoadXML(items[i].path);

This can be achieved asynchronously as follows:

var loaded = 0;
for (var i = 0; i < items.length; i++) {  
  asyncLoadXML(, function(xml) {
    item.xml = xml;
    if (loaded++ == items.length) {
var itemsLoaded = function() {

The declaration of itemsLoaded can still happen after the reference in JavaScript because var declarations are promoted to the top of the function.  In other languages you may need to declare itemsLoaded first, or make it a separate method of your object.


About austinfrance

Technical Developer @ RedSky IT / Explorer Software
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s