Matias Forbord avatar

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

codeluggage

Published: 17 Mar 2018 › Updated: 17 Mar 2018Fetching data from API with Javascript promises and await: explained with gifs

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


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

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

Written by

Engineering for social impact. Building an open educational gif platform.

Read more #javascript posts


Best Posts From Matias Forbord

We have not curated any of codeluggage's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Matias Forbord