Skip to content

Instantly share code, notes, and snippets.

@8bitDesigner
Created June 3, 2014 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 8bitDesigner/c0ed753b93e80e56d49e to your computer and use it in GitHub Desktop.
Save 8bitDesigner/c0ed753b93e80e56d49e to your computer and use it in GitHub Desktop.
# In the class
class Model
fetch: (options = {}) ->
opts = _.extend({}, options)
_(opts).defaults
method: 'GET'
url: _.result(@, 'url')
cancellableHttpRequest(opts).then(_(@parse).bind(@)).then(_(@set).bind(@))
# A helper method for allowing cancellable HTTP requests
cancellableHttpRequest = (opts) ->
dfd = $q.defer()
req = $http(opts)
# Wrap the request promise with our promise
req.then (res) -> dfd.resolve(res)
req.catch (res) -> dfd.reject(res)
dfd.promise.cancel = -> dfd.reject('cancelled')
return dfd.promise
# And usage in your app:
req = model.fetch(some: 'opts')
$scope.$on '$destroy', req.cancel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment