Codementor Events

Swift — Write beautiful Async code, with Promises

Published Oct 30, 2017Last updated Apr 28, 2018

Async code sucks…

fetchUserId({ id in
    fetchUserNameFromId(id, success: { name in
        fetchUserFollowStatusFromName(name, success: { isFollowed in
            // The three calls in a row succeeded YAY!
            reloadList()
        }, failure: { error in
            // Fetching user ID failed
            reloadList()
        })
    }, failure: { error in
        // Fetching user name failed
        reloadList()
    })
}) {  error in
    // Fetching user follow status failed
    reloadList()
}
🙉🙈🙊#callbackHell

It is hard to write, hard to read, hard to reason about.
A pain to maintain


Enters then 🎬

fetchUserId()
    .then(fetchUserNameFromId)
    .then(fetchUserFollowStatusFromName)
    .then(updateFollowStatus)
    .onError(showErrorPopup)
    .finally(reloadList)

By using a then keyword that enables you to write aSync code that reads like an English sentence.

Async code becomes concise , flexible, maintainable. And dare I say beautiful ❤️

Writing your own Promise 💪

Wondering what fetchUserId() is?
It is a simple function that returns a strongly typed promise :

func fetchUserId() -> Promise<Int> {
    return Promise { resolve, reject in
        doSomethingAsync { resolve(object: userId) } 
    }
}

Here you would typically replace the dummy doSomethingAsync function by your network request ❤

Now you can use it like so :

fetchUserId().then { id in
    print("UserID : \(id)")
}.onError { e in
    print("An error occured : \(e)")
}.finally {
    print("Everything is Done :)")
}

Bonus 🤓

If we want this to be beautiful , it should read like an english sentence
We can do this by extracting our blocks into separate functions :

fetchUserId()
    .then(printUserID)
    .onError(showErrorPopup)
    .finally(reloadList)

#goodbyeCallbackHell

For more info checkout the github repo here :

then 🎬, an Elegant Async code for Swift library

More goodness ❤️

then is part of a series of lightweight libraries aiming to make developing iOS Apps a breeze :

  • View Layout : Stevia 🍃
  • Json Parsing : Arrow 🏹
  • JSON WebServices : ws ☁️

Originally posted here

Discover and read more posts from Sacha Durand Saint Omer
get started
post commentsBe the first to share your opinion
Show more replies