Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save mfrancois3k/752362a7b5ec82a8ff3fe94c0889ab3d to your computer and use it in GitHub Desktop.

Select an option

Save mfrancois3k/752362a7b5ec82a8ff3fe94c0889ab3d to your computer and use it in GitHub Desktop.
Async JavaScript basics: Promises and async/await
// @ts-nocheck
/* eslint-disable */
// Asynchronous JavaScript basics
// Contrary of Synchronous
// Synchronous code runs line by line, instantly: eg
function logSum(a, b) {
console.log(a + b)
}
logSum(1, 2)
logSum(2, 2)
logSum(3, 2)
logSum(4, 2)
// Why do we use async?
// Calling other services: eg:
// 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
// Get a list of authors
const listAuthorsUrl = 'http://api.quotable.io/authorsblabla'
// Get a random quote of the first author in the list
const authorRandomQuoteUrl = (author) => {
return `https://api.quotable.io/random?author=${author}`
}
const axios = require('axios')
// The promise way (The old way)
// You have to chain them if you need to use
// multiple promises that depend on each other
axios
.get(listAuthorsUrl)
.then((response) => {
const firstAuthorSlug = response.data.results[0].slug
return firstAuthorSlug
})
.then((firstAuthorSlug) => {
return axios.get(authorRandomQuoteUrl(firstAuthorSlug))
})
.then((response) => {
console.log(response.data)
})
.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 axios.get(listAuthorsUrl)
const firstAuthorSlug = authorListResponse.data.results[0].slug
const randomQuoteFromAuthor = authorRandomQuoteUrl(firstAuthorSlug)
const randomQuoteResponse = await axios.get(randomQuoteFromAuthor)
const quote = randomQuoteResponse.data
console.log(quote)
} 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