Collect array of successful promises

雨燕双飞 提交于 2020-01-06 14:59:28

问题


I'm using PromiseKit 3.0 in Swift and I have an array of promises [Promise<Int>]. I want to gather up all the promises that succeed into a single promise. Promise<[Int]>.

Both when and join reject if even one contained promise rejects. According to the docs, I'm supposed to be able to use join and the error will contain an array of the fulfilled values, but in Swift the error contains all the promises that were passed in, not the fulfilled values.

Any help would be appreciated.


回答1:


I see now I need a new function:

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
}


来源:https://stackoverflow.com/questions/33526239/collect-array-of-successful-promises

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!