Search code examples
backbone.js

backbone.fetch using "return" only returns undefined instead of the specific value


Hi i'm new to backbonejs,

I created a function to validate sessions and have if and else statements through my routes when calling this function

var validateSession = function(){
    var session = new sessionCollection();
    session.fetch( {
        success : function(){
            return true;
        },
        error : function(){
            CarRentalApp.trigger('admin:login');
            return false;
        }
    } );
};

the problem is the "return" statement is not working out for me. Instead of returning true or false, it returns undefined instead. Am I missing something?


Solution

  • You can also use $.Deferred()

    var validateSession = function(){
        var defer = $.Deferred();
        var session = new sessionCollection();
        session.fetch( {
            success : function(){
                defer.resolve(true);
            },
            error : function(){
                defer.resolve(false);
            }
        });
        return defer.promise();
    };
    

    And then:

    $.when(validateSession()).done(function(result){
    });