Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Created November 21, 2017 17:57
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 KinoAR/cea5461c18c1a1e396a7650005b80bc4 to your computer and use it in GitHub Desktop.
Save KinoAR/cea5461c18c1a1e396a7650005b80bc4 to your computer and use it in GitHub Desktop.
An example of async and await when compared to callbacks.
//Async Await Example JS
//Server Data
const cats = {
Tim: {breed: "Persian"},
Meowth: { breed: "Meowth" },
Terry: {breed: "Bob Cat"}
}
//Call back Example
function getCatBreed(catName, callback) {
callback(cats[catName].breed);
}
function logUpperCaseBreed(catName) {
//Write callback function to log breed
getCatBreed(catName, function (breed) {
console.log(breed.toUpperCase());
})
}
//Output cat breed
getCatBreed("Tim", function (breed) {
console.log(breed);
});
//Output uppercase breed
logUpperCaseBreed("Tim");
//Async Await
async function getCatBreed2(catName) {
return cats[catName].breed;
}
async function logUpperCaseBreed2(catName) {
//get the data and simple console.log
const breed = await getCatBreed2(catName);
console.log(breed.toUpperCase());
}
//Output cat name
getCatBreed2("Tim").then(breed => { console.log(breed) });
//Output uppercase breed
logUpperCaseBreed2("Tim");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment