Skip to content

Instantly share code, notes, and snippets.

@chygoz2
Created October 18, 2018 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chygoz2/efd264cd41baa4e820bbbb3e2d6e9895 to your computer and use it in GitHub Desktop.
Save chygoz2/efd264cd41baa4e820bbbb3e2d6e9895 to your computer and use it in GitHub Desktop.
Gist demonstrating the use of Promises and async/await to handle asynchronous operations in loops
import axios from 'axios'
const API_ENDPOINT = 'https://sample-flights-api.com/cities/'
async function getAirports (cityCodes) {
let promises = []
let airports = []
cityCodes.forEach(city => {
let promise = new Promise(async (resolve, reject) => {
try {
let { data } = await axios.get(`${API_ENDPOINT}city`)
airports = [...airports, ...data]
resolve()
} catch (err) {
reject(err)
}
})
promises.push(promise)
})
try {
await Promise.all(promises)
return airports
} catch (err) {
console.log(err)
}
}
const cities = ['ABV', 'LOS', 'ENU']
// whatever we want to do with the list of airports, maybe just write them out to the console
console.log(getAirports (cities))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment