Skip to content

Instantly share code, notes, and snippets.

@danielt1263
Last active October 6, 2018 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielt1263/2b19e59beaf480535596 to your computer and use it in GitHub Desktop.
Save danielt1263/2b19e59beaf480535596 to your computer and use it in GitHub Desktop.
//
// PromiseKitAdditions.swift
//
// Created by Daniel Tartaglia on 11/4/15.
// Copyright © 2018. MIT License.
//
import PromiseKit
extension Promise {
typealias PendingPromise = (promise: Promise<T>, fulfill: (T) -> Void, reject: (ErrorType) -> Void)
}
/**
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 { values.append($0) }
.always {
--countdown
if countdown == 0 {
if values.isEmpty { reject(AnyError.Any) }
else { fulfill(values) }
}
}
}
}
}
public enum AnyError: ErrorType {
case Any
}
/**
Repeatedly 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 satisfies 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($0) }
}
else { loop() }
}
}
.error { reject($0) }
}
loop()
}
}
@tpgmeligmeyling
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment