The Spring '14 release of the Force.com platform introduces, amongst a lot of other great enhancements, Visualforce Remote Objects. Very simply, this new feature allows a developer to perform CRUD operations on Salesforce SObject records using javascript, no Apex controller required. It really is incredible stuff, and opens the platform even further to cutting edge frameworks and technologies. (Andrew Fawcett has a great writeup of Remote Objects, and highlights a lot of their advantages, as well as some reasons to be cautious.)

I've enjoyed playing around with Remote Objects while they're in developer preview, but I've found myself missing the ability to work with promises. Ever since Kevin Poorman opened my eyes to their utility, I've found it hard to use regular old callbacks. With that in mind, I've created a quick little function to augment Remote Objects with the ability to return promises.

Use

The code is all available on github.

After including jQuery (required for the deferred support), and makeDeferredProvider.js, you're ready to get started.

The regular flow for Visualforce Remote Objects is (per the release notes):

var wh = new SObjectModel.Warehouse();

// Use the Remote Object to query for 10 warehouse records
wh.retrieve({ limit: 10 }, function(err, records){
    if(err) alert(err.message);
    else {
        alert (records);
    }
});

Using promises, the flow is just a bit different:

makeDeferredProvider();

var wh = SObjectModel.deferredObject('Warehouse');;

// Use the Remote Object to query for 10 warehouse records
var whp = wh.retrieve({ limit: 10 });

whp.then(
// The first function is invoked when the promise is successfully fulfilled
    function(records){
        console.log(records);
    },
// The second function is invoked when the promise is rejected
    function(err) {
        console.log(err);
    }
});

That's a bit more verbose, and in this simple case, promises aren't worth the effort. Read up more here, or here to really start to get the advantages promises offer.

The usual caveats apply here: we're messing with the internal workings of Salesforce pages. And in this case, we're doing so on a developer preview technology. Things may break. I've worked with this a lot over the past week, and it's been solid, but there could be holes. And Salesforce could change things (and break my code) before GA.

Again, the code is available on github, so fork and improve it.