How to use PromiseKit for Swift

Dimitar Stefanovski
4 min readFeb 7, 2019

--

Photo by Daniel von Appen on Unsplash

PromiseKit is a popular third-party library for Swift and Objective-C programming language, and many developers are using this library to simplify the asynchronous tasks they have in their apps. Promises allows us to control the whole asynchronous background process with his powerful closure syntax for chaining multiple async functions.

What is a promise?

Promise is a generic way of structuring code that could take long time to run, and might succeed or fail, or in other words a Promise is a functional abstraction of a fail-able asynchronous operation.

Waiting for a async function

Where it is using?

One of the main reasons for using Promises in our app is when we have multiple callback functions in our code. We all know that async functions will execute simultaneously right away but we don’t know when and who of the functions will finish first. What if we want to change the order and priority of the functions or we want one function to call after another has finished (chaining of async functions)?

Are you familiar with this code?

In the example code we have three nested functions that gets called one after another. First function func fetchJSON(fromURL: , completion:) returns JSON data, then we pass that JSON data into the second function to fetch specific info for a user func fetchUserData(for username:, completion:) and after that we call third function to login the current user func loginUser(user: , completion:)

This is called a callback hell or pyramid of doom 🔥. This is not clean code and if you want to write clean structured code then Promises are the best choice for this type of problems, and in the next section I will explain the common promise patterns, how to create a promise and how to chain multiple promises.

How to create a Promise

Let’s see the first fetch function from the above code:

Assuming that you have already installed the PromiseKit library and included in your project, how can we wrap this function to return a promise?

It’s simple …

We create another function promiseFetchJSON() -> Promise<[String: Any]> that returns a Promise of generic type <T>, in our case because we want to fetch some JSON data the return type will be of type <[String: Any]>. In the body of the function we will call the fetchJSON() with the same functionality:

Now you are wondering what is the seal object? The seal object that the Promise initializer provides to you defines many methods for handling completion handlers.

A promise has to have fulfill and reject methods defined for the promise to be valid. Next we will convert the other functions to return a promise:

We have successfully wrapped all three functions to return a Promise, next we’ll see how we can use this new functions in our code.

Using Promises

Main purpose of Promises are chaining them together in a structural manner.

Here is a typical promise chain:

firstly is just a syntax to make code more readable and in this closure we pass the first promise function promise1().

then is another way to structure completion handlers that help us to easy understand asynchronous operations. If we return a promise in a then closure, then the next then waits on that promise before continuing. If one of the promises fails to resolve then the whole promise chain fails.

The chain ends in the done closure and that means that all of the promises are fulfilled successfully.

Phew… a lot of then’s

Finally we can use this syntax to wrap up our custom Promise functions and chain them together:

Look how clean this is compared to the nested functions above. With the power of the PromiseKit syntax we have refactored the code for more readability.

Conclusion

Asynchronous programming in iOS can be a pain 🤕 for a beginner programmer especially if you are not familiar with callbacks. A lot of nesting of function can occur and that leads to the famous callback hell or spaghetti code 🤷‍♂️. This can be avoided using appropriate techniques and libraries that are available at the moment.

One of the solution is using promises and there are many implementation for promises in Swift, one of them is the popular PromiseKit library for Swift and ObjC. PromiseKit let you write code as series of actions based on events and let your code look clean and beautiful. Promises allows us to control the whole asynchronous background process with his powerful closure syntax for chaining multiple async functions. For more information about using PromiseKit library please visit the official GitHub page.

I hope my code demonstration helped you for better understanding of the PromiseKit library and if you have any suggestions and comments feel free to post them below. 👏

If you are interested to see a real world example where Promises can be used please visit my post about Downloading images in Swift using PromiseKit and Alamofire.

--

--

Dimitar Stefanovski

👨‍💻Full-Stack Software Developer currently specializing in  iOS Development