Promisekit: Extension to add wait promise.

Created on 17 Mar 2017  Â·  5Comments  Â·  Source: mxcl/PromiseKit

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?

Most helpful comment

This would be my preference:

return firstly {
    someMethod()
}.then { object in
    after(seconds: 1.5).then{ object }
}.then { object in
    //…
}

All 5 comments

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
    //…
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

victoraraujo01 picture victoraraujo01  Â·  3Comments

dboydor picture dboydor  Â·  4Comments

guidedways picture guidedways  Â·  4Comments

zvonicek picture zvonicek  Â·  3Comments

rlam3 picture rlam3  Â·  5Comments