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.