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
51 lines
1.4 KiB
//
|
|
// Promise+Delay.swift
|
|
// then
|
|
//
|
|
// Created by Sacha Durand Saint Omer on 09/08/2017.
|
|
// Copyright © 2017 s4cha. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
import Dispatch
|
|
|
|
extension Promise {
|
|
|
|
public func delay(_ time: TimeInterval) -> Promise<T> {
|
|
let p = newLinkedPromise()
|
|
syncStateWithCallBacks(
|
|
success: { t in
|
|
Promises.callBackOnCallingQueueIn(time: time) {
|
|
p.fulfill(t)
|
|
}
|
|
},
|
|
failure: p.reject,
|
|
progress: p.setProgress)
|
|
return p
|
|
}
|
|
}
|
|
|
|
extension Promises {
|
|
public static func delay(_ time: TimeInterval) -> Promise<Void> {
|
|
return Promise { (resolve: @escaping (() -> Void), _: @escaping ((Error) -> Void)) in
|
|
callBackOnCallingQueueIn(time: time, block: resolve)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension Promises {
|
|
|
|
static func callBackOnCallingQueueIn(time: TimeInterval, block: @escaping () -> Void) {
|
|
if let callingQueue = OperationQueue.current?.underlyingQueue {
|
|
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).asyncAfter(deadline: .now() + time) {
|
|
callingQueue.async {
|
|
block()
|
|
}
|
|
}
|
|
} else {
|
|
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + time) {
|
|
block()
|
|
}
|
|
}
|
|
}
|
|
}
|