2015-11-04 48 views
0

我在Swift中使用PromiseKit 3.0,我有一組承諾[Promise<Int>]。我想把所有成功的承諾都彙集成一個承諾。 Promise<[Int]>收集成功的承諾數組

whenjoin如果連一個都包含諾言拒絕,則拒絕。根據文檔,我應該可以使用join,並且錯誤將包含所實現值的數組,但在Swift中,錯誤包含所有傳入的promise,而不是實現的值。

任何幫助,將不勝感激。

回答

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 
}