We all have come across nested network callbacks which looks something like this
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”.
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”.
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.
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.
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. 😀😀😀