Last active
June 7, 2023 05:35
-
-
Save decentraliser/9d969808aa27d33052a9418fe9ae416d to your computer and use it in GitHub Desktop.
Async JavaScript basics: Promises and async/await
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
// Asynchronous JavaScript basics | |
// Asynchronous programming is a way to execute code | |
// without blocking the execution of the rest of the program. | |
// We commonly use the asynchronous syntax when we need to | |
// => Get data from another website or API | |
// => Retrieving / storing data in a database | |
// => Write / Read files from file system | |
// Example | |
// Definition of the API used in this example: https://github.com/lukePeavey/quotable | |
// URL returning a list of authors | |
const listAuthorsUrl = "https://api.quotable.io/authors" | |
// Get a random quote from one author | |
const authorRandomQuoteUrl = (author) => { | |
return `https://api.quotable.io/random?author=${author}` | |
} | |
// The promise way (The old way) | |
// You have to chain them if you need to use | |
// multiple promises that depend on each other | |
fetch(listAuthorsUrl) | |
.then((response) => response.json()) | |
.then((parsedResponse) => { | |
const secondAuthorSlug = parsedResponse.results[1].slug | |
return secondAuthorSlug | |
}) | |
.then((secondAuthorSlug) => { | |
return fetch(authorRandomQuoteUrl(secondAuthorSlug)) | |
}) | |
.then((authorQuoteResponse) => authorQuoteResponse.json()) | |
.then((parsedAuthorQuoteResponse) => { | |
return console.log( | |
"Quote from second author, using the promise way", | |
parsedAuthorQuoteResponse | |
) | |
}) | |
.catch((error) => console.log("I CAUGHT AN ERROR", error)) | |
// The async/await way (The modern way) | |
// The async modifier is added to the function declaration | |
// The await modifier is added before asynchronous function calls | |
async function getRandomQuoteFromFirstAuthorInTheList() { | |
try { | |
const authorListResponse = await fetch(listAuthorsUrl) | |
const parsedAuthorListResponse = await authorListResponse.json() | |
const thirdAuthorSlug = parsedAuthorListResponse.results[3].slug | |
const randomQuoteFromAuthorUrl = authorRandomQuoteUrl(thirdAuthorSlug) | |
const randomQuoteResponse = await fetch(randomQuoteFromAuthorUrl) | |
const parsedRandomQuoteResponse = await randomQuoteResponse.json() | |
return console.log( | |
"Quote from second author, using the async/await way", | |
parsedRandomQuoteResponse | |
) | |
} catch (error) { | |
console.log("CAUGHT YA", error) | |
} | |
} | |
getRandomQuoteFromFirstAuthorInTheList() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment