I was looking for a way to insert a delay into a promise chain. I wasn't sure I could do it directly using after(...) and ended up writing this extension:
extension Promise {
func wait(_ interval:TimeInterval) -> Promise<T> {
return after(interval: interval).then {
return self
}
}
}
Not sure if it's correct but it allowed me to writ code like this:
return self.contentView.runFinishedAnimation()
.wait(0.5)
.then { () -> Void in
let dataAnalysis = DataAnalysisViewController()
self.navigationController?.pushViewController(dataAnalysis, animated: true)
}
Is there a better way to do this?
This is how I do it:
return self.contentView.runFinishedAnimation()
.then { after(interval: 0.5) }
.then { () -> Void in
let dataAnalysis = DataAnalysisViewController()
self.navigationController?.pushViewController(dataAnalysis, animated: true)
}
Though I'd probably write the whole thing like this:
return firstly {
contentView.runFinishedAnimation()
}.then {
after(interval: 0.5)
}.then {
self.show(DataAnalysisViewController(), sender: self)
}
Cool. Thanks for the suggestions.
How would you pass along a promise variable through the wait promise?
Ended up implementing like this and it works great:
func returnObjectAfterWait(object:Any, waitTime:TimeInterval) -> Promise<Any>{
return Promise { fulfill, reject in
after(interval:waitTime).then {
fulfill(object)
}
}
}
And then:
return firstly {
someMethod()
}.then { object -> Promise<Any>
return returnObjectAfterWait(object:object, waitTime:1.5)
}.then { object -> Void in
[use object here]
}
This would be my preference:
return firstly {
someMethod()
}.then { object in
after(seconds: 1.5).then{ object }
}.then { object in
//…
}
Most helpful comment
This would be my preference: