Created
October 18, 2018 08:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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