我正在使用promisekit 3.0来帮助以一种干净的方式链接alamofire回调。目标是从网络调用开始,并承诺返回一个urls数组。
然后,我希望根据需要执行网络调用,以找到我正在寻找的下一个链接。一旦找到这个链接,我就可以把它传递到下一个步骤。
这部分是我被困的地方。
我可以在数组中选择我想要的任意索引,但是在返回正确的信息之前,我无法确定循环以保持它的运行。
我试着从这个obj-c的例子中学习,但是我没能让它迅速地发挥作用。
https://stackoverflow.com/a/30693077/1079379
他是我所做的更具体的例子。
Network.sharedInstance.makeFirstPromise(.GET, url: NSURL(string: fullSourceLink)! )
.then { (idArray) -> Promise<AnyObject> in
let ids = idArray as! [String]
//how do i do that in swift? (from the example SO answer)
//PMKPromise *p = [PMKPromise promiseWithValue: nil]; // create empty promise
//only thing i could do was feed it the first value
var p:Promise<AnyObject> = Network.sharedInstance.makePromiseRequestHostLink(.POST, id: ids[0])
//var to hold my eventual promise value, doesn't really work unless i set it to something first
var goodValue:Promise<AnyObject>
for item in ids {
//use continue to offset the promise from before the loop started
continue
//hard part
p = p.then{ returnValue -> Promise<AnyObject> in
//need a way to check if what i get is what i wanted then we can break the loop and move on
if returnValue = "whatIwant" {
goodvalue = returnValue
break
//or else we try again with the next on the list
}else {
return Network.sharedInstance.makeLoopingPromise(.POST, id: item)
}
}
}
return goodValue
}.then { (finalLink) -> Void in
//do stuck with finalLink
}有人能告诉我如何正确地构造这个吗?
筑巢承诺是要避免的反模式吗?在这种情况下,什么是最好的方法。
发布于 2015-12-08 00:59:10
解决我的特殊问题的关键是使用"when“函数。直到你输入的所有电话都完成为止。这张地图使人更容易看(并在我的脑海中思考)
}.then { (idArray) -> Void in
when(idArray.map({Network.sharedInstance.makePromiseRequest(.POST, params: ["thing":$0])})).then{ link -> Promise<String> in
return Promise { fulfill, reject in
let stringLink:[String] = link as! [String]
for entry in stringLink {
if entry != "" {
fulfill(entry)
break
}
}
}
}.then {
}
}发布于 2015-11-24 19:40:17
我终于把你的帖子和你发布的链接结合起来看出来了。这是可行的,但如果有人对适当的解决方案有意见,我会很高兴的。
func download(arrayOfObjects: [Object]) -> Promise<AnyObject> {
// This stopped the compiler from complaining
var promise : Promise<AnyObject> = Promise<AnyObject>("emptyPromise")
for object in arrayOfObjects {
promise = promise.then { _ in
return Promise { fulfill, reject in
Service.getData(stuff: object.stuff completion: { success, data in
if success {
print("Got the data")
}
fulfill(successful)
})
}
}
}
return promise
}在这个例子中,我唯一没有做的就是保留接收到的数据,但是我假设您可以用现在的结果数组来完成这个任务。
https://stackoverflow.com/questions/33465884
复制相似问题