Parallel API calls in JavaScript
Although JavaScript is single-threaded, it is relatively simple to avoid blocking the thread by writing code in an asynchronous style through the use of functions with an async keyword that returns a promise and only awaiting when you need it.
For example, the following code contains an API call in an async function.
private async CallAPI() {
const response = await axios.get('https://fooapi.com/Films')
console.log(response.data)
}
If we wanted to call two APIs then we could do the following.
private async CallAPI() {
const response = await axios.get('https://fooapi.com/Films')
const response2 = await axios.get('https://fooapi.com/Music')
console.log(response.data)
console.log(response2.data)
}
However because both API calls are being immediately awaited, this will result in the execution of the function stopping while it waits for the result of the first API call before making the second.
As we don't need that response to make the second API call, we can improve the performance of the code by moving the await keywords to the point we actually need the responses. Both API calls will now be made in parallel rather than the second waiting for the first to finish.
private async CallAPI() {
const response = axios.get('https://fooapi.com/Films')
const response2 = axios.get('https://fooapi.com/Music')
console.log(await response.data)
console.log(await response2.data)
}
Call an API for each item in an array in parallel
Those initial examples were quite easy to understand, but what if we have a scenario where you get a list of films showing at the cinema on a particular day and display the show times for each? You have two APIs at your disposal; The first returns all the films and the second returns the showtimes for a given film.
To get all the data you need you first need to call the API to get the films and then loop through them to call the second API and get the show times.
interface Film {
id: string
name: string
showtimes: ShowTime[]
}
interface ShowTime {
date: Date
}
class FilmService {
public async GetShowtimes(): Promise<Film[]> {
const filmResponse = axios.get('https://fooapi.com/Films')
const films: Film[] = []
for (let e of (await filmResponse).data) {
console.log("Get Showtimes")
const showTimes = await axios.get(
`https://fooapi.com/Films/${e.id}/ShowTimes`
)
console.log("Got Showtimes")
films.push({
id: e.id,
name: e.name,
showtimes: showTimes.data,
})
}
return films
}
}
// Output
// Get Showtimes
// Got Showtimes
// Get Showtimes
// Got Showtimes
// Get Showtimes
// Got Showtimes
The problem with this code though is that its execution length will be the films API call response time + (showtime API response time * the number of films).
As each call to the second API have no dependencies on each other, it doesn't make any sense for them to have to be performed sequentially in the loop.
Instead, we can refactor for loop to be a map calling an async function which returns the new array and make use of Promise.all() to ensure they have all completed before returning the results.
interface Film {
id: string
name: string
}
interface FilmWithShowtime extends Film {
showtimes: ShowTime[]
}
interface ShowTime {
date: Date
}
class FilmService {
public async GetShowtimes(): Promise<FilmWithShowtime[]> {
const filmResponse = await axios.get('https://fooapi.com/Films')
const films: FilmWithShowtime[] = await Promise.all(
filmResponse.data.map(async (e: Film) => {
return await this.getFilmWithShowtimes(e)
})
)
return films
}
private async getFilmWithShowtimes(film: Film): Promise<FilmWithShowtime> {
console.log("Get Showtimes")
const showTimes = await axios.get(
`https://fooapi.com/Films/${film.id}/ShowTimes`
)
console.log("Got Showtimes")
return {
id: film.id,
name: film.name,
showtimes: showTimes.data,
}
}
}
// Output
// Get Showtimes
// Get Showtimes
// Get Showtimes
// Got Showtimes
// Got Showtimes
// Got Showtimes
The API calls for show times will now app be made in parallel reducing the overall execution time of the code.