Using Swift 5.5 Async Await to Fetch REST API

Alfian Losari
13 min readMay 31, 2021
Callback vs Async Await

As an iOS developer, most probably you already have lot of experiences to fetch REST API from multiple endpoints. In some instances, the call to the API endpoints need to be in sequential order as they need the response of previous API call to be passed in HTTP Request.

Let me give you an illustation for such scenario with these given steps:

  • Fetch IP address of the user from Ipify API.
  • Passing the IP address, fetch IP Geolocation data from FreeGeoIP API containing the country code.
  • Passing the Country Code, fetch the Country Detail from API.

If the final code we ended written will have 3 callbacks that are nested like the picture below, then welcome to Pyramid of Doom aka callback hell! The code is not easily readable, complicated, and harder to maintain as the codebase growth. Let’s say we need to use country detail response to fetch another API, we will add the 4th callback making the nesting become even much deeper.

Pyramid of Doom aka Callback Hell

The pyramid of doom callbacks problem has already been raised as one of the most requested issue that the Swift Language should eliminate. At 2017, Chris Lattner (Swift creator) had even written the Swift Concurrency Manifesto discussing his visions and goals to handle concurrency with imperative code using async await.

Finally with the accepted Swift Evolution Proposal (SE-0296), Async Await has been implemented in Swift 5.5 (Currently still in development as this article is written). The proposal provides the motivation to tackle 5 main problems:

  • Pyramid of doom.
  • Better error handling.
  • Conditional execution of asynchronous function.
  • Forgot or incorrectly call the callback.
  • Eliminating design and performance issue of synchronous API because of callbacks API awkwardness.

Async Await provides the mechanism for us to run asynchronous and concurrent functions in a sequential way. This will help us to eliminate pyramid of doom callback hell and…



Alfian Losari

Mobile Developer and Lifelong Learner. Currently building super app @ Go-Jek. Xcoding with Alfian at