1

PromiseKit 版本:4.0

Xcode 版本: 8.3.2

我最近开始使用 PromiseKit。

实际上,我正在创建一个轮询 HTTP 请求,该请求返回“已完成”或“未完成”。

我必须在每 1 秒后继续进行 HTTP 调用,持续 5 秒。

我需要实现的是,如果任何 1 个电话给我完成状态,我将返回已完成(“完成”)。但是如果我所有的请求都给了我“notCompleted”的响应,我需要返回reject("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 中编写上述代码。

4

1 回答 1

1

这是一种使用 Promises 进行基本循环的方法...来自我的要点:https ://gist.github.com/dtartaglia/2b19e59beaf480535596

我认为您需要做的就是确保您的 Promise producer ( 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()
    }
}
于 2017-05-29T03:27:40.767 回答