PromiseKit版本:4.0
Xcode版本: 8.3.2
我最近开始使用PromiseKit。
实际上,我正在创建一个轮询HTTP请求,返回时会给出“已完成”或“未完成”。
我必须在每1秒后继续拨打HTTP电话,持续时间为5秒。
我需要实现的是,如果任何一个电话给我完成状态,我将返回履行(“已完成”)。但如果我的所有请求都给我一个“未完成”的回复,我需要返回拒绝(“notCompleted”)
return Promise<T> { fulfilled, reject
let timer1 = Timer.scheduledTimer(withTimeInterval: TimeInterval(1), repeats: true) { timer in
pArr.append(Promise<T> { f, r in
doSomeAsyncTask { T in
if success {
f(T)
fulfilled(T)
timer.invalidate()
} else {
r(ErrorNotCompleted)
}
}
// timeout option
_ = after(interval: TimeInterval(15)).then(execute: { () -> Void in
reject(timeoutForConfirmation)
})
})
}
Timer.scheduledTimer(withTimeInterval: TimeInterval(5), repeats: false) { timer in
timer1.invalidate()
timer.invalidate()
when(resolved: pArr).then { results in
let count = results.filter({ result -> Bool in
return result.boolValue
}).count
if count == 0 {
// TODO: then reject here
reject(ErrorNotCompleted)
}
}.catch { error in
print(error)
}
}
}
timer1.fire()
我如何实现这一目标?
是否有更好的方法在PromiseKit中编写上述代码。
答案 0 :(得分:1)
这是一种使用Promises进行基本循环的方法......这是我的要点:https://gist.github.com/dtartaglia/2b19e59beaf480535596
我认为您需要做的就是确保您的承诺制作人(body
)在进行网络呼叫之前有适当的延迟。
/**
Repeadetly evaluates a promise producer until a value satisfies the predicate.
`promiseWhile` produces a promise with the supplied `producer` and then waits
for it to resolve. If the resolved value satifies the predicate then the
returned promise will fulfill. Otherwise, it will produce a new promise. The
method continues to do this until the predicate is satisfied or an error occurs.
- Returns: A promise that is guaranteed to fulfill with a value that satisfies
the predicate, or reject.
*/
func promiseWhile<T>(pred: (T) -> Bool, body: () -> Promise<T>, fail: (() -> Promise<Void>)? = nil) -> Promise<T> {
return Promise { fulfill, reject in
func loop() {
body().then { (t) -> Void in
if !pred(t) { fulfill(t) }
else {
if let fail = fail {
fail().then { loop() }
.error { reject($0) }
}
else { loop() }
}
}
.error { reject($0) }
}
loop()
}
}