Skip to content

Instantly share code, notes, and snippets.

@jkulton
Last active August 24, 2022 02:45
Show Gist options
  • Save jkulton/8523102d091a39536346b9c823449db5 to your computer and use it in GitHub Desktop.
Save jkulton/8523102d091a39536346b9c823449db5 to your computer and use it in GitHub Desktop.
callback example
<html>
<body>
<script>
class FakeXMLHttpRequest {
constructor() {
this.events = [];
}
open() {}
addEventListener(eventType, cb) {
this.events.push(cb);
}
send() {
// send() sends your request and then once the response comes in...
// - sets `this.response` to what it got back
// - executes the 'load' callback you gave it
//
// it's important to note your other code has
// kept running while all this is going on though
const cb = this.events[0];
setTimeout(() => {
this.response = '["Jay","Steve","Jordan","Jon"]';
cb();
}, 0); // I just fake it and return immediately
// but even though this is 0, this callback
// doesn't execute until JS takes it off
// the event queue and executes it
}
}
class Model {
constructor() {
this.contacts = [];
this.cacheContacts();
}
cacheContacts = () => {
const request = new FakeXMLHttpRequest();
request.open('GET', 'http://localhost:3000/api/contacts');
request.addEventListener('load', event => {
const data = JSON.parse(request.response);
data.forEach(contact => this.contacts.push(contact));
});
request.send();
};
}
document.addEventListener('DOMContentLoaded', () => {
const model = new Model();
console.log(model.contacts); // Logs empty array
console.log(model.contacts.length); // Logs 0
setTimeout(() => { // This callback is executed _after_ the one where you update the array items
console.log(model.contacts); // Logs array with items
console.log(model.contacts.length); // Logs 4
}, 0);
});
</script>
</body>
</html>
@rafiq
Copy link

rafiq commented Jan 25, 2022

Great explanation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment