Last Updated: February 25, 2016
·
1.193K
· camachgk

Preventing callback queue with $.promise

We use a lot of $.promises with the code that we write. Sometimes, we run into problems where we want to change the callback or prevent a queue of callbacks from being created while the promise is pending.

To handle this kind of functionality, we designed an "on deck" pattern that tracks the most recent callback for the promise to be executed on completion.

class Dummy
  constructor : (@promise) ->
    @promise.then(
      _.bind @executeOnDeck, @, 'done',
      _.bind @executeOnDeck, @, 'fail'
    )

  setOnDeck : (type, callback) ->
    @["onDeck#{ type }"] = callback
    if @promise.state() isnt 'pending'
      @promise[type] _.bind @executeOnDeck, @, type

  executeOnDeck : (type) -> 
    @["onDeck#{ type }"]?.apply @, arguments

Now, we can manage track the most recent callback and ensure only one is kept while the promise is pending.

deferred = $.Deferred()
dummy = new Dummy deferred.promise()

dummy.setOnDeck 'done', -> console.log '1st callback'
dummy.setOnDeck 'done', -> console.log '2nd callback'

deferred.resolve() 
# console - '2nd callback'

dummy.setOnDeck 'done', -> console.log '3rd callback'
# console - '3rd callback'