Skip to content

Instantly share code, notes, and snippets.

@gbishop
Created August 12, 2010 14:30
Show Gist options
  • Save gbishop/521051 to your computer and use it in GitHub Desktop.
Save gbishop/521051 to your computer and use it in GitHub Desktop.
/* this is an attempt to use the new then and when functions in Dojo 1.5 to handle a chain of async
actions. The scenario is open 2 databases, get a record from the 2nd db, write a record to the 1st that uses data from that record. save it. This is 4 async steps.
*/
// dfetch is a hack to get a database fetch method wrapped up as a deferred. We could add a
// method to the db class to make this a bit prettier
function dfetch(db, query) {
var def = new dojo.Deferred();
db.fetch({
query: query,
onComplete: function(items) {
def.callback(items);
}
});
return def;
}
// likewise dsave is a deferred version of the save method
function dsave(db) {
var def = new dojo.Deferred();
db.save({
onComplete: def.callback,
onError: def.errback
});
return def;
}
// here is the code for the 4 steps
var main = function() {
var db1, db2;
// step 1: get the 1st db
uow.getDatabase({database: 'BigWords', collection: 'gbTry'}).then(function(db) {
db1 = db;
// step 2: get the 2nd db
return uow.getDatabase({database: 'BigWords', collection: 'AlphabetSoupLessons', mode: 'r'});
}).then(function(db) {
db2 = db;
// setp 3: fetch an item
return dfetch(db2, {});
}).then(function(items) {
console.log('items', items[0]);
var record = { name: 'set1', value: [ items[0]._id ] };
db1.newItem(record);
// setp 4: save the new record
return dsave(db1);
}).then(function() {
console.log('all done');
});
};
dojo.ready(main);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment