function myDataGetterThingy(done) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyStateChange === 4) {
try {
var res = JSON.parse(xhr.responseText);
// Handel an error status
if (xhr.status !== 200) {
return done(xhr.status, res);
}
// Successful response
done(null, res);
} catch(e) {
// JSON parse error
done(e);
}
}
};
xhr.onerror = function() {
done('Request failed');
};
xhr.open('GET', 'foo.json', true);
xhr.send(null);
}
myDataGetterThingy(function(err, res) {
if (err) {
return console.error(err);
}
// Do some other awesome stuff with the data
});
Let's add a new async task and to a few things at once:
function anotherAsyncee(done) {
// Do some stuff
done();
}
myDataGetterThingy(function(err, res) {
if (err) {
return console.error(err);
}
anotherAsyncee(function(err) {
if (err) {
return console.error(err);
}
console.log('Success!!!');
});
});
var complete = 0;
function done(err, res) {
if (err) {
return console.error(err);
}
complete++;
console.log(res);
if (complete === 2) {
console.log('Success!!!');
}
}
myDataGetterThingy(done);
anotherAsyncee(done);