我正在使用 promisekit 3.0 以一种干净的方式帮助链接 alamofire 回调。目标是从网络调用开始,并承诺返回一个 url 数组。
然后,我希望根据需要对这些 url 执行网络调用,以找到我正在寻找的下一个链接。找到此链接后,我可以将其传递到下一步。
这部分是我卡住的地方。
我可以在数组中选择一个我知道有我想要的东西的任意索引,但我无法弄清楚循环以使其继续运行,直到返回正确的信息。
我尝试从这个 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
}
有人可以告诉我如何正确地构造它吗?
嵌套承诺是否应该避免这种反模式?在这种情况下,最好的方法是什么。