This post is from a low-reputation account and contains an unverified outbound link. Be cautious before clicking external links.

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

Words
189
Reading
1 min
Listen
Play
8y


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

Fetching data from API with Javascript promises and await: explaine... | Ecency