Will Ember Data send additional requests for records already pending?


#1

I looked into the RESTAdapter and it sends AJAX requests and returns promises for each call to find(). Is Ember Data intelligent about pending requests, so that if it already has a pending promise awaiting resolution for a particular query, it won’t request another from the adapter? For example, find(type, id) might see that a find(type) request is already pending, and wait.

Here’s a simplified version of my use case:

App.CatalogRoute = Ember.Route.extend({
	model: function(params) {
		return Ember.RSVP.hash({
			categories: this.store.find('categories'),
			catalog: this.store.find('catalog', params.catalog_id)
		}).then(function(hash) {
			return hash.catalog;
		});
	}
});

The catalog payload returns a catalog and a set of items in the catalog, which belong to categories. I’m concerned that if the catalog request resolves first, then Ember Data will start making requests for categories.


#2

The solution is to load categories before the catalog, using assimilation of promises. The requests cannot be made simultaneously.

model: function(params) {
	return this.store.find('category').then(function() {
		return this.store.find('catalog', params.catalog_id);
	}.bind(this));
}

Also, after digging through the code, it turns out that Ember Data is smart about not sending simultaneous requests for the same particular records.

For the curious: in Ember Data v1.0.0-beta.6, findById results in a call to buildRecord where a record doesn’t yet exist in the store, before the call to the adapter, and a subsequent call to findById will return the pending promise, which is detected in fetchRecord (all in this file).

This behaviour applies to findById and findByIds, but I don’t think it applies to findAll or findQuery. I imagine it is a tenet of Ember Data and REST that find-all and find-by-query requests can return various results, and two subsequent (or even simultaneous) requests for the same query are not guaranteed to return the same records. Though I’m not sure. Unless there’s a spec stating otherwise about REST requests, it’s best that Ember Data doesn’t let a pending find(type) eclipse a find(type, id).