Backbone: Wait for multiple fetch to continue

backbone.js, javascript, jquery

Solution

Use jQuery deferreds:

var deferreds = [];
for (var i = 1; i <= last_page; i++) {
  deferreds.push(this.fetch({add: true, data: {page: i}}));
};

$.when.apply($, deferreds).done(function() {
  ...
  <CODE HERE>
  ...
}

(I haven't actually tested this but I think it should work.)

jQuery documentation on `when`:

Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

And another answer that might help: How do you work with an array of jQuery Deferreds?

Problem

I fetch collection of multiple pages and I am looking for a way to know when all fetchs are done. Here is what my collection looks like: ``` app.collections.Repos = Backbone.Collection.extend({ model: app.models.Repo, initialize: function(last_page){ this.url = ('https://api.github.com/users/' + app.current_user + '/watched'); for (var i = 1; i <= last_page; i++) { this.fetch({add: true, data: {page: i}}); }; }, ... ``` Any idea how I could achieve this with clean code?

Original source

Related problems