Skip to content

Commit

Permalink
Add utility function for waiting for a promise to complete
Browse files Browse the repository at this point in the history
  • Loading branch information
EricRabil committed Jul 25, 2022
1 parent a7f1282 commit e7c5c1d
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions Sources/Pwomise/Extensions/Promise+Wait.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//
// File.swift
//
//
// Created by Eric Rabil on 7/25/22.
//

import Foundation

public extension Promise {
enum TimeoutError: Error { case timedOut }

func wait(upTo time: DispatchTime) throws -> Output {
var completion: Completion!
let semaphore = DispatchSemaphore(value: 0)
var semaphoreLocked: Bool {
if semaphore.wait(timeout: .now()) == .success {
semaphore.signal()
return false
}
return true
}
always {
completion = $0
if semaphoreLocked {
semaphore.signal()
}
}.resolving(on: DispatchQueue.global())
if semaphore.wait(timeout: time) == .success {
// finished in time, signal and return
semaphore.signal()
} else {
// did not finish in time, throw
throw TimeoutError.timedOut
}
return try completion.get()
}
}

0 comments on commit e7c5c1d

Please sign in to comment.