Skip to content

Instantly share code, notes, and snippets.

@NickJosevski
Created November 25, 2012 02:29
Show Gist options
  • Save NickJosevski/4142165 to your computer and use it in GitHub Desktop.
Save NickJosevski/4142165 to your computer and use it in GitHub Desktop.
CoffeeScript version of jQuery.ajaxQueue
# <reference path="jquery-1.8.0.min.js" />
# from: https:#gist.github.com/1039247
###
* jQuery.ajaxQueue - A queue for ajax requests
*
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
###
(($) ->
# jQuery on an empty object, we are going to use this as our Queue
ajaxQueue = $({})
$.ajaxQueue = (ajaxOpts, stopQueueAfterError) ->
jqXHR = null
dfd = $.Deferred()
promise = dfd.promise()
stopQueueAfterError = stopQueueAfterError || true
#queue our ajax request
ajaxQueue.queue( doRequest )
# add the abort method
promise.abort = (statusText) ->
# proxy abort to the jqXHR if it is active
if jqXHR
jqXHR.abort statusText
# if there wasn't already a jqXHR we need to remove from queue
queue = ajaxQueue.queue()
index = $.inArray doRequest, queue
if index > -1
queue.splice index, 1
# and then reject the deferred
dfd.rejectWith ajaxOpts.context || ajaxOpts, [ promise, statusText, "" ]
promise
# run the actual query
doRequest = (next) ->
failCallback = ->
next()
return
if stopQueueAfterError
failCallback = ->
# cannot continue to process queue after an error
return
jqXHR = $.ajax(ajaxOpts)
.done(dfd.resolve)
.fail(dfd.reject)
.then(next, failCallback)
promise
)(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment