Skip to content

Instantly share code, notes, and snippets.

@andrunix
Created January 30, 2014 17:17
Show Gist options
  • Save andrunix/8713747 to your computer and use it in GitHub Desktop.
Save andrunix/8713747 to your computer and use it in GitHub Desktop.
Firebase findAll
findAll: function() {
var sports = {};
var sportsRef = new Firebase(FBURL + '/sports');
sportsRef.once('value', function(snapshot) {
sports = snapshot.val();
});
return sports;
}
@ifandelse
Copy link

If you want to retain the "sync-like-nature" of a return value from findAll, you can return a promise:

// (this is using the "Q" lib to create a raw promise)
var findAll = function() {
    var deferred = Q.defer();
    var sportsRef = new Firebase(FBURL + '/sports');
    sportsRef.once('value', function(snapshot) {
        deferred.resolve(snapshot.val());
    });
    return deferred.promise;
};

findAll().then(function(sports) { /*do stuff with sports */ });

However - plain callbacks are fine, too (don't let anyone tell you they aren't :-)):

var findAll = function(done) {
    var sports = {};
    var sportsRef = new Firebase(FBURL + '/sports');
    sportsRef.once('value', function(snapshot) {
        done(snapshot.val());
    });
};

findAll(function(sports) { /*do stuff with sports */ });

plain callbacks become an issue primarily when you have a string of nested callbacks - at that point it's a design smell. Promises can help flatten those nested callbacks out, but they don't necessarily address the design smell if one exists.

@ifandelse
Copy link

I should have noted that the callback based approach is often better handled without anonymous functions:

var findAll = function(done) {
    var sports = {};
    var sportsRef = new Firebase(FBURL + '/sports');
    sportsRef.once('value', function(snapshot) {
        done(snapshot.val());
    });
};

var doCrapWithSports = function(sports) {
    // Console log all the things
    console.log(sports);
}

findAll(doCrapWithSports);

Also - my first example using promises was not covering the error side of things. You can deferred.reject instead of resolve if you have an issue (or if it times out, for ex). Highly recommend covering both the success (resolve) and failure (reject) side of a promise so that you don't end up in a limbo-edge-case state.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment