Swift Parallel Programming With PromiseKit

Kaan Özdemir
2 min readOct 17, 2022

--

Hi there,

Today, I would like to tell you what I know about PromiseKit.

Why do we need paralel programming?

While executing a task on the right hand, we would want to execute another task. This could be asynchronously image downloading or we may want to wait one request’s response and continue with the some logic according to response and then one more request again etc. Right next to this PromiseKit will help us.

Let’s take a look at PromiseKit.

You can chain logics or request or whatever you want with PromiseKit. It’s so easy!

Let’s imagine we are waiting for a user login and then we will change the app flow according to login status.

Let’s do it with closures and Promises. Then let’s see the difference.

We have LoginStatus, Result and ProfileItem enums, login and fetchProfileItems function that returns some datas after 2 seconds. You can image like a fake service requests.

Please take a look the codes.

Code with closures looks little bit messy, right?

We create a Promise with the returning value called loginPromise and itemsPromise.

In loginPromise, we create promise with the LoginStatus return. And we return it. Inside of the promise, we can make some logics or requests etc. We fill resolver value with the data like using fullfill function. LoginPromise is done.

In itemsPromise, we create promise with the ProfileItem array return. And same with the loginPromise, we return it. Inside of itemsPromise, some logics and we call fullfill function and give array. ItemsPromise is done too.

Now we will chain this 2 promises using firstly keyword. To see clearly, I write it down below again.

firstly { 
login(username: username, password: password)
}.then { loginStatus in
fetchProfileItems(with: loginStatus)
}.done { items in
print("Fetched profile items :", items)
}
.catch { error in
print(error.localizedDescription)
}

Let’s try to read.

Firstly login and then with this loginStatus fetch profile items, when it’s done print it to console. Of course we handle error situation at the end of done.

Easy, right?

If you like it, please follow me to keep posted for new articles.

Bye bye.

--

--