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
.
.