-
Notifications
You must be signed in to change notification settings - Fork 6
Promise
Yuki Takei edited this page Oct 11, 2016
·
2 revisions
The Promise object is used for asynchronous computations. A Promise represents a value which may be available now, or in the future, or never.
In Slimane, There is no Promise library in codes. So need to install Thrush which is a light weight Promise Implementation without threading.
It also has similar apis to the ES promise. For more detail, visit https://github.com/noppoMan/Thrush
import PackageDescription
let package = Package(
name: "MyApp",
dependencies: [
.Package(url: "https://github.com/noppoMan/Thrush.git", majorVersion: 0, minor: 2),
]
)
Here is an asynchronously database manipulate example with Promise
import Thrush
extension DB {
func execute(sql: String) -> Promise<FooResult> {
return Promise<FooResult> { resolve, reject in
let onThread = { ctx in
do
ctx.storage["result"] = try blockingSqlQuery(sql)
} catch {
ctx.storage["error"] = error
}
}
let onFinish = { ctx in
if let error = ctx.storage["error"] as? Error {
reject(error)
return
}
resolve(ctx.storage["result"] as! FooResult)
}
Process.qwork(onThread: onThread, onFinish: onFinish)
}
}
}
let db = DB(host: "localhost")
db.execute("insert into users (id, name) values (1, 'jack')").then {
print($0)
}
.`catch` {
print($0)
}
.finally {
print("Done")
}