Promise 代表了一个在创建时未必已知的值的代理。它可以关联处理程序到异步操作的最终成功值或失败原因。这使得异步方法可以像同步方法一样返回值:异步方法不是返回最终值,而是返回一个在未来某个时间点将具有值的承诺。
iPromise 的 Promise 类的实现符合 JavaScript 规范。
将以下行复制到您的 Podfile 中
pod 'iPromise', '~> 1.1'
请确保还添加 !use_frameworks
func computeAnswerToLifeTheUniverseAndEverything() -> Int {
// ... computing
return 42
}
async(computeAnswerToLifeTheUniverseAndEverything)
.success { result in
// 7.5 million years later
print("Ok, but what is \(result) the answer to?")
}
enum Error: ErrorType {
case FailureAndError
}
async {
return 0.5
}.then({ result in
if result > 0.5 {
print("This is quite a large number")
}
else {
// we simply cannot accept a number this small!
throw Error.FailureAndError
}
}).then({ result in
// this won't be called
}).then({ result in
// this won't be called
}).failure({ (error) -> Double in
// but this will
switch error as! Error {
case .FailureAndError:
print("Long computation has failed miserably :(")
}
// let's recover
return 0.6
}).then ({ result -> Double in
if result > 0.5 {
print("This is quite a large number")
}
return 0.1
})
注意:我在此允许使用简写方法(sucesss()
和 failure
)。目前请在返回承诺时使用稍微语法繁杂的 then()
。
Promise { fulfill, reject in
fulfill(10)
}.then({ result in
return Promise { fulfill, reject in
fulfill(100)
}
}).then({ result in
// result is 100!
print(result)
})
文档可在这里找到 http://cocoadocs.org/docsets/iPromise/1.1.0/,但因为它是由代码注释生成的,您还可以阅读代码,没有那么难 :)
查看 LICENCE