我试图编写一个返回承诺的函数:
func sample() -> Promise<AnyObject> {
return Promise(1)
.then { _ -> Void in
debugPrint("foo")
}.then { _ -> Void in
debugPrint("foo")
}
}在最后一条语句中,我得到了一个错误:
Declared closure result 'Void' (aka '()') is incompatible with contextual type 'AnyPromise'我的印象是,“那么”应该含蓄地回报一个承诺;我的想法是不是错了?我是否应该像这样明确地回报一个承诺?:
func sample() -> Promise<AnyObject> {
return Promise(1)
.then { _ -> Void in
debugPrint("foo")
}.then { _ -> Promise<AnyObject> in
debugPrint("foo")
return Promise(1)
}
}谢谢
发布于 2016-05-15 02:56:22
then(_:)返回的承诺与闭包的返回值匹配。
func sample() -> Promise<AnyObject> {
return Promise(1)
.then { _ -> Void in
debugPrint("foo")
}.then { _ -> Void in
debugPrint("foo")
}
}让我重新研究一下你的方法。
func sample() -> Promise<AnyObject> {
let p1: Promise<AnyObject> = Promise(1)
let p2: Promise<Void> = p1.then { _ -> Void in
debugPrint("foo")
}
let p3: Promise<Void> = p2.then { _ -> Void in
debugPrint("foo")
}
return p3
}现在您可以看到Promise<AnyObject>的预期返回类型与实际的Promise<Void>返回类型不匹配。
如果您想让一个方法返回Promise<AnyObject>,那么承诺链中的最后一个承诺必须返回AnyObject。
func sample() -> Promise<AnyObject> {
return firstly { _ -> Void in
debugPrint("foo")
}.then { _ -> Void in
debugPrint("foo")
}.then { _ -> AnyObject in
1
}
}发布于 2016-05-15 02:47:48
then调用返回您在它的调用中指定的任何内容,在第一个示例中返回Void。
对于您的第二次尝试,您更接近了,但是您返回了一个不相关的Promise,您不得不第二次使用1来实现它。
尝试下面的代码:
func sample() -> Promise<AnyObject> {
return Promise<AnyObject> { fulfill, reject in
return Promise<AnyObject>(1)
.then { _ -> Void in
debugPrint("foo")
}.then { _ -> Void in
debugPrint("foo")
}
}
}这将第二个Promise嵌入到第一个,因此现在您的then将按照顺序运行,以及在代码中其他地方调用该函数时添加到函数返回的承诺中的任何其他内容。
https://stackoverflow.com/questions/37233531
复制相似问题