Paginating a Backbone collection This is part of a class for paginating a Backbone collection.

The paginateTo method is for paginating to a model id. It returns the model if it's already in the collection, otherwise it checks with the server that it exists. If so, it requests subsequent pages until it's loaded into the collection.

How would you refactor this method to make it clearer?

paginateTo: (id, dfd, check) -&gt;
  dfd ?= new $.Deferred
  return dfd.resolve(model) if model = @get(id)
  check ?= @checkModelExists(id)
  check.done =&gt;
    @once 'sync', =&gt; @paginateTo(id, dfd, check)
    @fetchNextPage()
  check.fail =&gt;
    dfd.reject()
  dfd.promise()

checkModelExists: (id) -&gt;
  url = @url() + '/' + id
  $.get url

fetchNextPage: -&gt;
  @page += 1
  @fetch { update: true, remove: false, data: { page: @page }}
You could do something like this

paginateTo: (id) -&gt;
  deferred   = new $.Deferred
  modelCheck = null

  modelExists = =&gt;
    modelCheck or= @checkModelExists id

  fetchUntilFound = =&gt;
    return deferred.resolve model if model = @get id
    modelExists().fail deferred.reject
    modelExists().done =&gt;
      @fetchNextPage().then fetchUntilFound, deferred.reject

  fetchUntilFound()
  deferred.promise()