Fetching data from API with Javascript promises and await: explained with gifs

in javascript •  7 years ago  (edited)

Fetching data from an API

API's are opening up and there's tons of examples on pages like https://github.com/toddmotto/public-apis

When working with API's, fetch is a common way to get the data it exposes. Other libraries serve a similar purpose, like Axios. There are have been many ways to do this throughout the ages, and although callbacks were common, Promises and more recently async/await is taking over. 

I recorded two short gifs to explain how a Promise can be used, as well as how much easier and smaller the code is by using await.


To get the data from this API, you could wrap it in a Promise:


const apiUrl = 'https://jobs.search.gov/jobs/search.json\?query\=nursing+jobs+in+ny'

// Making a promise
const apiPromise = new Promise((resolve, reject) => {
 // Using a promise
 fetch(apiUrl).then((result) => {
   console.log('Fetched!', new Date().getTime())
   resolve(result.json())
 }).catch((error) => {
   console.log('Failed fetch', new Date().getTime())
   reject(error)
 })
})


https://gifsplanation.com/gifs/javascript-fetch-from-an-api-with-promises


Here's the same 2 promises resolved (fetch and result.json()) using await:


const apiUrl = 'https://jobs.search.gov/jobs/search.json\?query\=nursing+jobs+in+ny' 

// await only works in an async function
async function getJobs() {
 try {
   const result = await fetch(apiUrl)
   const json = await result.json()
   console.log(json)
 } catch(error) {
   console.log(error)
 }
}


https://gifsplanation.com/gifs/javascript-fetch-from-an-api-with-await

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Congratulations @codeluggage! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

Are you a DrugWars early adopter? Benvenuto in famiglia!
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Congratulations @codeluggage! You received a personal award!

Happy Steem Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

Downvote challenge - Add up to 3 funny badges to your board
Vote for @Steemitboard as a witness to get one more award and increased upvotes!