Skip to content

Instantly share code, notes, and snippets.

@davepermen
Created June 14, 2013 13:57
Show Gist options
  • Save davepermen/5781996 to your computer and use it in GitHub Desktop.
Save davepermen/5781996 to your computer and use it in GitHub Desktop.
Tiny Async Handler in JS
var get = function (path, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (this.status === 200) {
callback(this.responseText);
}
};
xhr.open('get', path);
xhr.send();
};
var articleSection = document.querySelector('#articles');
whenall(function (on) {
get(window.location.pathname, on('model'));
get('/template/articles.html', on('template'));
setTimeout(on('timeout'), 2000);
}, function (data) {
articleSection.innerHTML = Mustache.to_html(data.template, JSON.parse(data.model));
});
var whenall = function (begin, end) {
var index = 0;
var results = {};
var on = function (name) {
++index;
return function (data) {
--index;
results[name] = data;
if (index === 0) {
end(results);
}
};
};
begin(on);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment