Search code examples
javascriptbackbone.jspromisemarionettedeferred

pass a collection instead of array to fetch().then() callback


Module which fetches data from the server and returns a Promise

MedicineManager.module("Entities", function (Entities, MedicineManager, Backbone, Marionette, $, _) {
    Entities.Suggestion = Backbone.Model.extend({
        default: {
            suggestion: ""
        }
    });

    Entities.SuggestionCollection = Backbone.Collection.extend({
        model: Entities.Suggestion,
        comparator: "suggestion"
    });

    var API = {
        getSuggestions: function (medicine) {
            var suggestions = new Entities.SuggestionCollection();
            suggestions.url="/medicine_suggestions/?id=" + medicine;
            return suggestions.fetch();
        }
    };

    MedicineManager.reqres.setHandler("suggestion:entities", function (medicine) {
        return API.getSuggestions(medicine);
    });

});


Module which calls the above module for getting fetched data

MedicineManager.module("MedicinesApp.Suggest", function (Suggest, MedicineManager,
    Backbone, Marionette, $, _) {


            MedicineManager.request("suggestion:entities", "paracetamol").then(function (medicines) {


            });
});


How do I get collection instead of an array as the parameter to the callback function in then() because the medicines parameter passed to the callback is giving an array after fetching the values.


Solution

  • Instead of directly returning the xhr promise, filter it via .then to set your collection as the promised value :

    var API = {
        getSuggestions: function (medicine) {
            var suggestions = new Entities.SuggestionCollection();
            suggestions.url="/medicine_suggestions/?id=" + medicine;
            return suggestions.fetch().then(function() {
                return suggestions;
            });
        }
    };
    

    The first argument (medicines) in MedicineManager.request(...).then(function (medicines) { }); will be your collection.