Fixing pyramid of doom/nested callbacks, Async-Await style

Vikash Anand
Apr 25 · 3 min read

We all have come across nested network callbacks which looks something like this

Nested network call with callback hell / pyramid of doom

Problem with the above code is that it creates a nested callbacks / pyramid of doom which is difficult to read and understand. A more elegant solution for nested network calls can be implemented using a technique called “Async-await”.

Nested network calls — Asyn-await style using semaphore

Above is the same nested network calls using “Async-await”, much cleaner and more readable as compared to the first code snippet, right?. Lets see how to implement this.

I found this technique in a youtube video named “Advanced Swift: Callback Hell Network Calls- Async Await Style Fix” posted by “Lets build that app”.

This technique is used in javascript and we will see here how this can be implemented in swift.So there are two ways in which this can be implemented

  1. Semaphore(create-wait-signal)
Async — await (Semaphore)

In the above implementation semaphore.wait() call makes sure that the current thread waits until the network call / session.datatask() closure get a callback and inside that callback, semaphore.signal() call resumes the waiting thread.This arrangement make sure that all network calls gets executed one after the other, maintaining their order.

Nested network calls — Asyn-await style using semaphore

An important thing here to keep in mind is that, all the network calls should be made on the same thread otherwise you will loose the nested callback feature.Also in the above code i have used a background queue to make sure that semaphore wait doesn’t block the main thread.So in your case if you are already on a different thread(thread other than main thread) then you can skip the above mentioned “switching to a background thread” logic.

2. DispatchGroup(create-enter-wait-leave)

Async — await (dispatch_group)
Nested network calls — Asyn-await style using dispatch_group

And this is how you make nested network calls without the hassle of nested callbacks.

Anyways that’s it for now and i hope you find this helpful. Here is the link for the complete source code. Thanks for reading. 😀😀😀

Vikash Anand

Written by

iOS Application Developer.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade