Created
November 21, 2017 17:57
-
-
Save KinoAR/cea5461c18c1a1e396a7650005b80bc4 to your computer and use it in GitHub Desktop.
An example of async and await when compared to callbacks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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