Swift — Write beautiful Async code, with Promises
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
then 🎬
EntersfetchUserId()
.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 :
Originally posted here