轮询异步任务,然后等待 1 次成功或所有响应都被拒绝

Polling for a async task and then waiting for either 1 success or all response rejected

PromiseKit 版本: 4.0

Xcode版本:8.3.2

我最近开始使用 PromiseKit。

实际上,我正在创建一个轮询 HTTP 请求,它在 returns 中给出 "completed" 或 "notCompleted"。

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

我需要实现的是,如果任何 1 个调用给我完成状态,我将 return 完成("completed")。但是如果我的所有请求都给我 "notCompleted" 的响应,我需要 return 拒绝("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中

这是一种使用 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([=10=]) }
                    }
                    else { loop() }
                }
            }
            .error { reject([=10=]) }
        }
        loop()
    }
}