Sometimes you want to get some data from several different API endpoints. In this example I will be using the Star Wars API to get information about some characters. See below.
const urls = [
"https://swapi.co/api/people/1",
"https://swapi.co/api/people/2",
"https://swapi.co/api/people/3",
"https://swapi.co/api/people/4",
]
Begin with an outline for the function. Do this so you can easily visualise what's happening. I use a try/catch block as it’s easily to see what’s going on.
Try/Catch
- Try - ‘Do this.’
- Catch - ‘Can’t do the try? Then do this instead.
const fetchData = async () => {
try {
} catch (error) {}
}
For this the catch block will console log the error with a message if the try fails.
const fetchData = async () => {
try {
} catch (error) {
console.log(‘ERROR’, error)
}
}
The serious business happens in the try block below.
const fetchData = async () => {
try {
const response = await Promise.all(urls.map(url => fetch(url)))
console.log(response)
} catch (error) {
console.log("Error", error)
}
}
- We create a variable
response
for holding our data. - Using the keyword await’. Await - ‘Go do this for me and come back.’
-
Promise.all method is used to tell the function to go and do all of the urls from our
urls
array. One at a time. - Using .map() array method to iterate over our array.
- We then pass each url into the
fetch()
. Seen asurl => fetch(url)
Logging the response you will see the promises have been fulfilled. Each url is hit. However we want the data in a format we can use. So there's one last thing to do. We must make the response a JSON object.
const fetchData = async () => {
try {
const response = await Promise.all(
urls.map(url => fetch(url).then(res => res.json()))
)
console.log(response)
} catch (error) {
console.log("Error", error)
}
}
Notice above we added .then(res => res.json()
. We use .then for chaining. Taking the response or 'res' which is returned once 'fetched'. Convert the response to JSON which we can use.
Code for you to try
const urls = [
"https://swapi.co/api/people/1",
"https://swapi.co/api/people/2",
"https://swapi.co/api/people/3",
"https://swapi.co/api/people/4",
]
const fetchData = async () => {
try {
const response = await Promise.all(
urls.map(url => fetch(url).then(res => res.json()))
)
console.log(response)
} catch (error) {
console.log("Error", error)
}
}
fetchData()
Top comments (4)
Excellent post David, This was really clear and straight to the point! love it!
Thank you Klajdi. Means lots!
Great explanation - thanks!
Thanks Sean glad you enjoyed!