问题
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