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 RestCountries.eu 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…

--

--

Alfian Losari

Mobile Developer and Lifelong Learner. Currently building super app @ Go-Jek. Xcoding with Alfian at https://alfianlosari.com