You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.4 KiB

  1. //
  2. // Promise+Delay.swift
  3. // then
  4. //
  5. // Created by Sacha Durand Saint Omer on 09/08/2017.
  6. // Copyright © 2017 s4cha. All rights reserved.
  7. //
  8. import Foundation
  9. import Dispatch
  10. extension Promise {
  11. public func delay(_ time: TimeInterval) -> Promise<T> {
  12. let p = newLinkedPromise()
  13. syncStateWithCallBacks(
  14. success: { t in
  15. Promises.callBackOnCallingQueueIn(time: time) {
  16. p.fulfill(t)
  17. }
  18. },
  19. failure: p.reject,
  20. progress: p.setProgress)
  21. return p
  22. }
  23. }
  24. extension Promises {
  25. public static func delay(_ time: TimeInterval) -> Promise<Void> {
  26. return Promise { (resolve: @escaping (() -> Void), _: @escaping ((Error) -> Void)) in
  27. callBackOnCallingQueueIn(time: time, block: resolve)
  28. }
  29. }
  30. }
  31. extension Promises {
  32. static func callBackOnCallingQueueIn(time: TimeInterval, block: @escaping () -> Void) {
  33. if let callingQueue = OperationQueue.current?.underlyingQueue {
  34. DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).asyncAfter(deadline: .now() + time) {
  35. callingQueue.async {
  36. block()
  37. }
  38. }
  39. } else {
  40. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + time) {
  41. block()
  42. }
  43. }
  44. }
  45. }