Simultaneous Network Calls with PromiseKit

Recently I’ve been working on a project where the networking layer is built around the promise based architecture using PromiseKit. There’s been a learning curve involved, but overall it has simplified and condensed our logic flows enormously. Today I ran into one one of those learning curves in the form of figuring out how best to handle multiple, simultaneous network calls while leveraging promises. This post is a trip through the process I took to solve that.

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 and combine the returned data into a single object used for processing when all are complete.

My hope was to have something similar to the Observable.zip functionality within RxSwift without having to lean 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. .then 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.

Final working solution:

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 calls data individually.

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

Hope this helps you out with any future network calls!

Credit for a lot of help in figuring this out goes to Jan Olbrich