callbackやerrbackをとるfunctionからjQueryのPromiseオブジェクトをつくる

doSomethingAndSucceed = (text, callback, errback) ->
  setInterval ->
    callback text
  , 1000
doSomethingAndFailed = (text, callback, errback) ->
  setInterval ->
    errback text
  , 1000

jQuery.deferrable(doSomethingAndSucceed, "succeeded", "__callback__", "__errback__").done (text) ->
  console.log text
jQuery.deferrable(doSomethingAndFailed, "failed", "__callback__", "__errback__").fail (text) ->
  console.log text;

#=> succeeded
#=> failed

上のようなことをしたかった。

jQuery.extend
  deferrable: ->
    deferred = @Deferred()
    callback = ->
      deferred.resolve.apply deferred, arguments
    errback = ->
      deferred.reject.apply deferred, arguments
    func = Array.prototype.shift.apply(arguments)
    args = []
    for argument in arguments
      if argument == "__callback__"
        args.push callback
        continue
      if argument == "__errback__"
        args.push errback
        continue
      args.push argument
    func.apply func, args;
    deferred.promise()

doSomethingAndSucceed = (text, callback, errback) ->
  setInterval ->
    callback text
  , 1000

doSomethingAndFailed = (text, callback, errback) ->
  setInterval ->
    errback text
  , 1000


jQuery.deferrable(doSomethingAndSucceed, "succeeded", "__callback__", "__errback__").done (text) ->
  console.log text

jQuery.deferrable(doSomethingAndFailed, "failed", "__callback__", "__errback__").fail (text) ->
  console.log text;

(JsFiddle)