Simultaneous Network Calls with PromiseKit

Awhile back I worked on a project where the networking layer was built around a promise-based architecture using PromiseKit. While building within it I needed to figure out how best to handle multiple, simultaneous network calls when using promises. This post is a trip through the process I took to solve that problem.

Disclaimer: I am by no means an expert in PromiseKit. If you find errors or know of a better solution please leave a comment below.

The requirement:

Execute multiple promise based network calls at the same time, and then combine the returned data into a single object once all calls are complete.

My hope was to have something similar to the functionality within RxSwift without having to dig into that library.

Attempted solutions:

What I started with was three independent functions which individually used the firstly { } execution pattern and handled their responses separately. This was by no means elegant.

Because the data that the three pieces were retrieving was tightly coupled I wanted to find a simpler way to trigger them all at once. At first I started looking into the .then function and testing to see if it would work. It is geared towards taking in some form of data, doing work if necessary, and then passing that data along though. So something like this wouldn’t work:

I needed something better.

What worked:

The ticket was actually a function I hadn’t known about before called when. This allows for multiple promise executions to be “queued” up in a way and all fired off simultaneously. Then you can be informed when they have all finished and use a capture list to access each call’s data individually.

After discovering the when(fulfilled: ) functionality I was able to come up with this final solution which ended up doing exactly what I needed.

Hope this helps you out with any future network calls using promises!

Credit for a lot of help in figuring this out goes to Jan Olbrich’s article.




iOS engineer @ Spotify

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alex Persian

Alex Persian

iOS engineer @ Spotify

More from Medium

Building a recursion-free world

Making a Cocoapod in Swift with an Objective-C .framework dependency

Everyone can code — Loop jumper

Preventing merge conflicts with XcodeGen for your xcode project using xcodeGen and project.yml file