-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add utility function for waiting for a promise to complete
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} | ||
} |