Skip to content

Instantly share code, notes, and snippets.

extension Foo {
static func promise() -> Promise<FooResult> {
return PromiseWithDelegate().promise
}
}
class PromiseWithDelegate: FooDelegate {
let (promise, seal) = Promise<FooResult>.pending()
private let foo = Foo()
func attempt<T>(maximumRetryCount: Int = 3, delayBeforeRetry: DispatchTimeInterval = .seconds(2), _ body: @escaping () -> Promise<T>) -> Promise<T> {
var attempts = 0
func attempt() -> Promise<T> {
attempts += 1
return body().recover { error -> Promise<T> in
guard attempts < maximumRetryCount else { throw error }
return after(delayBeforeRetry).then(on: nil, attempt)
}
}
return attempt()
let timeout = after(seconds: 4)
race(when(fulfilled: fetch(url:url)).asVoid(), timeout).then {
//…
}
let waitAtLeast = after(seconds: 0.3)
firstly {
fetch(url: url)
}.then {
waitAtLeast
}.done {
//…
}
fetch(url: url).then(on: .global(QoS: .userInitiated)) {
//then closure executes on different thread
}
firstly {
when(fulfilled: promise1(), promise2())
}.done { result1, result2 in
//…
}
firstly {
fetch(url: url)
}.get { data in
//…
}.done { data in
// same data!
}
func fetch(url: URL) -> Promise<Data> {
return Promise { seal in
URLSession.shared.dataTask(with: url!) { data, _, error in
seal.resolve(data, error)
}.resume()
}
}
firstly {
firstly {
fetch(url: url)
}.ensure {
cleanup()
}.catch {
handle(error: $0)
}
firstly {
return fetch(url:url)
}.then{
...
}