您的问题是您的闭包正在返回Void
而不是Promise<T>
. 该then
块不希望返回任何内容,因此它会继续进行而不等待承诺被履行或拒绝。
这是一个完整的例子。您可以将其粘贴到 PromiseKit 游乐场进行测试。
var zipcode: String?
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
firstly {
return DataManager.reverseGeoCodePromise("42.527328", longitude: "-83.146928")
}.then { (data: String) -> Promise<String> in
// ^ I expect to receive a string. I promise to return a string
zipcode = data
// ^ Store zip code so it can be used further down the chain
print("Returned from reverseGeoCodePromise: \(data)")
return DataManager.getEnviroUVWithZipPromise(zipcode!)
}.then { (data: String) -> Promise<String> in
// ^ I expect to receive a string. I promise to return a string
print("Returned from getEnviroUVWithZipPromise: \(data)")
return DataManager.getCurrentForZipPromise(zipcode!)
}.then { (data: String) -> Void in
// ^ I expect to receive a string. I return nothing
print("Returned from getCurrentForZipPromise: \(data)")
}.always {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}.error { error in
switch error {
case DataManagerError.FailedDueToX:
print("got an error")
default:
print("unknown error")
}
}
示例自定义错误类型:
enum DataManagerError: ErrorType {
case FailedDueToX
}
示例数据管理器承诺:
class DataManager {
static func reverseGeoCodePromise(lat: String, longitude: String) -> Promise<String> {
return Promise { fulfill, reject in
if 1 == 1 {
fulfill("48073")
} else {
reject(DataManagerError.FailedDueToX)
}
}
}
static func getEnviroUVWithZipPromise(zip: String) -> Promise<String> {
return Promise { fulfill, reject in
if 1 == 1 {
fulfill("Two")
} else {
reject(DataManagerError.FailedDueToX)
}
}
}
static func getCurrentForZipPromise(zip: String) -> Promise<String> {
return Promise { fulfill, reject in
if 1 == 1 {
fulfill("Three")
} else {
reject(DataManagerError.FailedDueToX)
}
}
}
}