3

I'm using Backbone.Marionette's request-response framework to fetch data in collection and then response it to the request object that request it, but obviously it doesn't wait for collection to get populated. And here is my code:

This is where it is requesting the data:

// Module: Timeline, ListController
var employees = App.request('employee:timeline');

and here is where i set my handler:

// Entities Module
App.reqres.setHandler('employee:timeline', function() {
    return API.getEmployeesForTimeline();
});

and here is my API's function:

getEmployeesForTimeline: function() {
    var employees = new Entities.EmployeeCollection();

    employees.fetch({
        success: function(employees) {
            returnEmployees(employees);
        }
    });

    function returnEmployees(employees) {
        // doing some things with employees collection
        return leaves;
    }
}
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
fre2ak
  • 329
  • 2
  • 8
  • 18

1 Answers1

8

Use a promise to pass the results back:

getEmployeesForTimeline: function() {
    var employees = new Entities.EmployeeCollection();
    var deferred = $.Deferred();
    employees.fetch({
        success: deferred.resolve
    });

    return deferred.promise();
}

// Entities Module: UNCHANGED
App.reqres.setHandler('employee:timeline', function() {
    return API.getEmployeesForTimeline();
});

//request data
var promise = App.request('employee:timeline');
promise.done(function(employees){
    //use employees
});
Creynders
  • 4,573
  • 20
  • 21