Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery plugin used to queue $.Deferred's Promise objects

jQuery queue plugin

Queuing ajax queries might sometimes be useful. Here is a coffeescript version based on $.Deferred objects.

Working sample can be found here: http://jsfiddle.net/wA6K8/1/

###*
* jQuery queue plugin v0.1
* ==========================
*
* Used to queue $.Deferred's Promise objects
* author @_dhar
###
(($) ->
class $.Queueable
constructor: (@builder, @args, @validator = -> yes) ->
promise: -> @builder(@args...).promise()
expose: -> @args
isValid: -> @validator(@args...)
$.queuedWhen = (queueables) ->
d = $.Deferred();
prev = null
deferredObjs = ((
do (q) ->
if not q instanceof $.Queueable
d.reject "#{q} is not a $.Queueable object", q
else
prev = if prev then prev.pipe -> q.promise() else q.promise()
prev.done -> d.notify q.expose()
prev.fail -> d.reject q.expose()
) for q in queueables when q.isValid() )
$.when(deferredObjs...).then -> d.resolve()
return d.promise()
)(jQuery)
###
* Sample 1: Create $.Queueable objects with custom builder, args and validator
###
queueables1 = [
new $.Queueable $.get, ['/echo/json/', {arg:'1', delay:1}]
new $.Queueable $.get, ['/echo/json/', {arg:'2', delay:1}]
new $.Queueable $.get, ['/echo/json/', {arg:'3', delay:1}]
]
$.queuedWhen(queueables1).then -> console.log 'all done'
###
* Sample 2: Create $.Queueable objects with custom builder, args and validator
###
doQuery = (url, arg) -> $.get(url, {arg: arg, delay: 1})
check = (url, arg, doIt) -> doIt
queueables2 = [
new $.Queueable doQuery, ['/echo/json/', '1', yes ], check
new $.Queueable doQuery, ['/echo/json/', '2', yes ], check
new $.Queueable doQuery, ['/echo/json/', '3', yes ], check
new $.Queueable doQuery, ['/echo/json/', '4', no ], check # this one won't be sent
new $.Queueable doQuery, ['/echo/fail/', '5', yes ], check # this one will fail
new $.Queueable doQuery, ['/echo/json/', '6', yes ], check
]
$.queuedWhen(queueables2).done(-> console.log 'all done').fail (q) ->
console.log 'something goes wrong...', q
###
* Sample 3: Create a custom $.Queueable object and override methods
###
class TestQueueable extends $.Queueable
constructor: (@id) ->
promise: -> $.post '/echo/json/', {id: @id, delay:1}
expose: -> @id
isValid: -> @id%2 is 0
someOtherMethod: -> console.log "someOtherMethod called on TestQueueable[#{@id}]"
queueables3 = [
new TestQueueable 1
new TestQueueable 2
new TestQueueable 3
new TestQueueable 4
new TestQueueable 5
new TestQueueable 6
new TestQueueable 7
]
$.queuedWhen(queueables3).done -> console.log "all done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.