From e7c5c1d652679b905b4922619b9b70e142f89c0f Mon Sep 17 00:00:00 2001 From: Eric Rabil Date: Mon, 25 Jul 2022 16:34:02 -0400 Subject: [PATCH] Add utility function for waiting for a promise to complete --- Sources/Pwomise/Extensions/Promise+Wait.swift | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Sources/Pwomise/Extensions/Promise+Wait.swift diff --git a/Sources/Pwomise/Extensions/Promise+Wait.swift b/Sources/Pwomise/Extensions/Promise+Wait.swift new file mode 100644 index 0000000..54f0166 --- /dev/null +++ b/Sources/Pwomise/Extensions/Promise+Wait.swift @@ -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() + } +}