Skip to content

Instantly share code, notes, and snippets.

@rewritten
Created November 11, 2014 20:45
Show Gist options
  • Save rewritten/7305c5e98fa6cd3790da to your computer and use it in GitHub Desktop.
Save rewritten/7305c5e98fa6cd3790da to your computer and use it in GitHub Desktop.
Wrap http with a global canceler.
# blatantly inspired and actually almost copied from
# https://www.exratione.com/2013/08/angularjs-wrapping-http-for-fun-and-profit/
# BEWARE: not tested in any way
# create the decorator
$cancellableHttp = ($delegate, $q) ->
$http = $delegate
canceler = null
# wrap plain $http(...) calls
wrapper = ->
# create a canceler if needed
canceler ||= $q.defer()
# add the canceler as a timeout
arguments[0] ||= {}
arguments[0].timeout ||= canceler.promise
# call the underlying implementation
$http.apply($http, arguments)
# wrap $http.get(...) and similar calls
for verb in ["get", "post", "put", "delete", "options"]
wrapper[verb] = ->
canceler ||= $q.defer()
# add the canceler as a timeout
arguments[0] ||= {}
arguments[0].timeout ||= canceler.promise
$http[verb].apply($http, arguments)
# add a cancelPending function that resolves the canceler
wrapper.cancelPending = ->
canceler.resolve()
$timeout ->
canceler = null
return
# return the wrapped $http
wrapper
# load the decorator in a config block
angular.module(yourModule)
.config ($provide) ->
$provide.decorator '$http', $cancellableHttp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment