Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Support for Swift Async/Await #205

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Sources/Promises/Promise+Async.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,59 @@ public extension Promise {
objCPromise.__addPendingObject(self)
}
}

#if swift(>=5.5)
#if canImport(_Concurrency)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public extension Promise {
func async() async throws -> Value {
try await withCheckedThrowingContinuation { continuation in
then { value in
continuation.resume(returning: value)
}.catch { error in
continuation.resume(throwing: error)
}
}
}
}

public extension Task {
func asPromise() -> Promise<Success> {
Promise<Success> { fulfill, reject in
fulfill(try await self.value)
}
}
}

@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public extension Promise {
typealias SwiftAsync = (@escaping (Value) -> Void, @escaping (Error) -> Void) async throws -> Void

/// Creates a pending promise and executes `work` block asynchronously on the given `queue`.
/// - parameters:
/// - queue: A queue to invoke the `work` block on.
/// - work: A block to perform any operations needed to resolve the promise.
convenience init(on queue: DispatchQueue = .promises, _ work: @escaping SwiftAsync) {
let objCPromise = ObjCPromise<AnyObject>.__onQueue(queue) { fulfill, reject in
Task {
do {
try await work({ value in
if type(of: value) is NSError.Type {
reject(value as! NSError)
} else {
fulfill(Promise<Value>.asAnyObject(value))
}
}, reject)
} catch let error {
reject(error as NSError)
}
}
}
self.init(objCPromise)
// Keep Swift wrapper alive for chained promise until `ObjCPromise` counterpart is resolved.
objCPromise.__addPendingObject(self)
}
}

#endif
#endif