Vlatko Ristovski
Vlatko Ristovski

Reputation: 111

Backbone fetching a collection using callbacks vs promises

I have a Location collection, and I have back a JSON response from the serve r on fetch including the root title with format:

{'locations':[
  {
  "id": 1,
  "address": 'first address'
},{
  "id": 2,
  "address": 'second address'
}
]}

I've read everywhere that is best practice to use promise's methods over backbone success and error callbacks but here is the thing. I have override the parse method on the Location collection to return the array, but it appears that using the promises methods the parse method isn't called at all. So for example:

var Locations = new Backbone.Collection.extend({...})
var locations = new Locations()
locations.fetch().then(function(response){
console.log(response)
})

returns an Object literal with property locations which has the value of the Array of locations. But if I use

locations.fetch({ 
success: function(response){
console.log(response)
}
})

I get the wanted behavior, that is the object with constructor Locations and all the models in it.

Plus if I remove the root title of the JSON response on the backend and remove the parse method override on the collection, with the promise methods I'm getting an object with constructor Array, while with the success callback I'm getting an object with constructor Locations.

So my question is, if it is better to use the promise's methods how to adopt them with the similar behavior as the success and error callbacks?

Requsted update:

Here is the parse function in the Locations collections

var Locations = new Backbone.Collection.extend({
parse: function(response){
return response['locations']
}
})

Upvotes: 0

Views: 760

Answers (1)

Spike
Spike

Reputation: 741

Use the collection directly:

locations.fetch().then(function(){
    console.log(locations);
})

The fetch method returns the jqXHR promise that makes the request, so it returns the raw response received from the server. The promise doesn't know about the parsing of the response.

The reason that passing a success callback as an option to fetch worked for you is: (See Collection.fetch documentation)

The options hash takes success and error callbacks which will both be passed (collection, response, options) as arguments.

So if use pass a success callback to fetch, the first argument is actually collection, not response.

Upvotes: 2

Related Questions