Skip to content

Instantly share code, notes, and snippets.

@phadej
Last active December 12, 2015 04:28
Show Gist options
  • Save phadej/4714638 to your computer and use it in GitHub Desktop.
Save phadej/4714638 to your computer and use it in GitHub Desktop.
How to do transactions with indexedDb using promises?
// Using moreUsable.js style
indexedDB.open(DBNAME, DBVERSION, DBSCHEMA)
.then(function(connection) {
return connection.transaction(["table1"]) // undefined -> readonly, state undefined also
.then(function(obj) {
return obj.transaction.get(obj.state, "table1", "foo");
})
.then(function(obj) {
return obj.state;
});
})
.then(function (value) {
console.log("everything went ok, got value", value);
}, function(e) {
console.error("something failed", e);
});
indexedDB.open(DBNAME, DBVERSION, DBSCHEMA)
.then(function(connection) {
return connection.transaction(["table1", "table2"], {}, true) // true for readwrite, {} for initial state
.then(function(obj) {
return obj.transaction.get(obj.state, "table1", "foo");
})
.then(function(obj) {
var newState = _.extend({}, obj.state, { foo: obj.value });
return obj.transaction.add(newState, "table2", { id: "bar", value : value.bar });
})
.then(function(obj) {
// don't do anything with state anymore, just return it
return obj.state;
});
})
.then(function (state) {
console.log("everything went ok, got state", state);
}, function(e) {
console.error("something failed", e);
});
/* I miss do-notation from Haskell. */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment