Clicky

iOS Dev Nugget 229 Promises

.

Need to run a code review on your codebase? Hire me

Heard of Promises?

If you haven't, here's an example of what promises help to improve:

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

With promises, you can write something like:

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

Basically, without the ever-increasing indentation, making flow control clearer.

Another example is when you fire off several network calls in parallel and only want to act (eg. display them on screen) when results from all of them have been returned. Promises let you do something like this:

whenAll(fetchHeaderInformation(), fetchBodyInformation(), fetchFooterInformation()).then { allInfo in
  //All the results are ready
}

The async example code above was taken from the freshOS repository README.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues