【问题标题】:Collect array of successful promises收集一系列成功的承诺
【发布时间】:2015-11-04 15:54:12
【问题描述】:

我在 Swift 中使用 PromiseKit 3.0,并且我有一系列的 Promise [Promise<Int>]。我想将所有成功的 Promise 收集到一个 Promise 中。 Promise<[Int]>.

whenjoin 都拒绝,即使其中一个包含 promise 也拒绝。根据文档,我应该能够使用 join 并且错误将包含一个已实现值的数组,但在 Swift 中,该错误包含所有传入的承诺,而不是已实现的值。

任何帮助将不胜感激。

【问题讨论】:

    标签: swift promisekit


    【解决方案1】:

    我知道我现在需要一个新功能:

    https://gist.github.com/dtartaglia/2b19e59beaf480535596

    /**
    Waits on all provided promises.
    
    `any` waits on all provided promises, it rejects only if all of the promises rejected, otherwise it fulfills with values from the fulfilled promises.
    
    - Returns: A new promise that resolves once all the provided promises resolve.
    */
    public func any<T>(promises: [Promise<T>]) -> Promise<[T]> {
        guard !promises.isEmpty else { return Promise<[T]>([]) }
        return Promise<[T]> { fulfill, reject in
            var values = [T]()
            var countdown = promises.count
            for promise in promises {
                promise.then { value in
                    values.append(value)
                }
                .always {
                    --countdown
                    if countdown == 0 {
                        if values.isEmpty {
                            reject(AnyError.Any)
                        }
                        else {
                            fulfill(values)
                        }
                    }
                }
            }
        }
    }
    
    public enum AnyError: ErrorType {
        case Any
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-07
      • 1970-01-01
      • 2018-10-03
      • 2017-02-19
      • 2016-09-02
      • 1970-01-01
      • 2013-10-23
      • 1970-01-01
      • 2018-03-18
      相关资源
      最近更新 更多