Have you ever dream to write asynchronous code like its synchronous counterpart?
AwaitKit is a powerful Swift library inspired by the Async/Await specification in ES8 (ECMAScript 2017) which provides a powerful way to write asynchronous code in a sequential manner.
Internally it uses PromiseKit to create and manage promises.
Requirements • Getting Started • Usage • Installation • Contribution • Contact • License
Requirements
- iOS 8.0+
- Xcode 8.0+
- Swift 4.0+
Getting Started
If you want have a quick overview of the project take a look to this blog post.
Put simply, write this:
let user = try! await(signIn(username: "Foo", password: "Bar"))
try! await(sendWelcomeMailToUser(user))
try! await(redirectToThankYouScreen())
print("All done!")
Instead of:
signIn(username: "Foo", password: "Bar")
.then { user in
return self.sendWelcomeMailToUser(user)
}
.then { _ in
return self.redirectToThankYouScreen()
}
.then { _ in
print("All done!")
}
Or worse, using the completion block imbrication hell style:
signIn(username: "Foo", password: "Bar") { user in
self.sendWelcomeMailToUser(user) { _ in
self.redirectToThankYouScreen() { _ in
print("All done!")
}
}
}
Usage
Async
The async
method yields the execution to its closure which will run in a background queue and returns a promise which will be resolved at this end of block.
Here a small example :
func setupNewUser(name: String) -> Promise<User> {
return async {
let newUser = try await(self.createUser(name))
let friends = try await(self.getFacebookFriends(name))
newUser.addFriends(friends)
return newUser
}
}
Here the setupNewUser
returns a promise with a user as value. If the end of async
block is executed the promise will be resolved, otherwise if an error occurred inside the async block the promise will be rejected with the corresponding error.
The async
block will catch the error thrown to reject the promise so you don't need to manage the await
exceptions. But if necessary, you can:
async {
do {
try await(self.loginOrThrown(username: "yannickl"))
}
catch {
print(error)
}
try await(self.clearCache())
}
Await
The await
method will executes the given promise or block and await until it resolved or failed.
do {
let name: String = try await {
Thread.sleep(forTimeInterval: 0.2)
if Int(arc4random_uniform(2) + 1) % 2 == 0 {
return "yannickl"
}
else {
throw NSError()
}
}
print(name)
}
catch {
print(error)
}
Custom queues
The async
and await
methods runs by default on a background concurrent queue. Of course, you can choose your own queues and call the following methods:
DispatchQueue.global(qos: .default).ak.async {
}
try DispatchQueue.global(qos: .default).ak.await {
}
When you use these methods and you are doing asynchronous, be careful to do nothing in the main thread, otherwise you risk to enter in a deadlock situation.
Installation
The recommended approach to use AwaitKit in your project is using the CocoaPods package manager, as it provides flexible dependency management and dead simple installation.
CocoaPods
Install CocoaPods if not already available:
$ [sudo] gem install cocoapods
$ pod setup
Go to the directory of your Xcode project, and Create and Edit your Podfile and add AwaitKit:
$ cd /path/to/MyProject
$ touch Podfile
$ edit Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
pod 'AwaitKit', '~> 4.0.0'
Install into your project:
$ pod install
If CocoaPods did not find the PromiseKit 4.5.1
dependency execute this command:
$ pod repo update
Open your project in Xcode from the .xcworkspace file (not the usual project file)
$ open MyProject.xcworkspace
Swift Package Manager
You can use The Swift Package Manager to install AwaitKit
by adding the proper description to your Package.swift
file:
import PackageDescription
let package = Package(
name: "YOUR_PROJECT_NAME",
dependencies: [
.Package(url: "https://github.com/yannickl/AwaitKit.git")
]
)
Note that the Swift Package Manager is still in early design and development, for more information checkout its GitHub Page.
Carthage
Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
You can install Carthage with Homebrew using the following command:
$ brew update
$ brew install carthage
To integrate AwaitKit into your Xcode project using Carthage, specify it in your Cartfile
:
github "yannickl/AwaitKit" ~> 4.0
Run carthage update
to build the framework and drag the built AwaitKit.framework
into your Xcode project.
Manually
Download the project and copy the AwaitKit
folder into your project to use it in. Note that you also need to download the PromiseKit library and import it to your project.
Contribution
Contributions are welcomed and encouraged ♡.
Contact
Yannick Loriot
License (MIT)
Copyright (c) 2016-present - Yannick Loriot
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.