Skip to content

Instantly share code, notes, and snippets.

@justintemps
Last active June 15, 2020 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justintemps/719ff469d8c863f47da591b23e97b24e to your computer and use it in GitHub Desktop.
Save justintemps/719ff469d8c863f47da591b23e97b24e to your computer and use it in GitHub Desktop.
Callbacks and Promises
// EXAMPLE 1: Simple AJAX call with callback
// Adapted slightly from https://eloquentjavascript.net/2nd_edition/17_http.html
function getURL(url, callback) {
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.addEventListener("load", function() {
if (req.status < 400)
callback(req.response);
else
callback(null, new Error("Request failed: " +
req.statusText));
});
req.addEventListener("error", function() {
callback(null, new Error("Network error"));
});
req.send(null);
}
// EXAMPLE 2: The gates of callback hell. Nested calls of getURL() to different endpoints.
function getRestaurants(zipcode, callback) {
getURL(
`https://www.ourserver.com/api/get-restaurants-by-zip?code=${zipcode}`,
function (data) {
var { restaurants } = data;
restaurants.forEach(function (restaurant) {
var { id } = restaurant;
getURL(
`https://www.ourserver.com/api/get-reviews-for-restaurant?id=${id}`,
callback
);
});
}
);
}
// EXAMPLE 3: Our getURL function re-written with Promises
function get(url) {
return new Promise(function (succeed, fail) {
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.addEventListener("load", function () {
if (req.status < 400) {
succeed(req.response);
} else {
fail(new Error("Request failed: " + req.statusText));
}
});
req.addEventListener("error", function () {
fail(new Error("Network error"));
});
req.send(null);
});
}
// EXAMPLE 4. Promises allow us to chain asynchronous code together
function getRestaurantsWithPromises(zipcode) {
return get(
`https://www.ourserver.com/api/get-restaurants-by-zip?code=${zipcode}`
).then((data) => {
var { restaurants } = data;
return Promise.all(
restaurants.map((restaurant) => {
var { id } = restaurant;
return get(
`https://www.ourserver.com/api/get-reviews-for-restaurant?id=${id}`
);
})
);
});
}
getRestaurantsWithPromises(79912)
.then((data) => doSomething(data))
.catch((error) => console.error(`Something went wrong: ${error.message}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment