about lock

31 views
Skip to first unread message

Eag Dra

unread,
Dec 29, 2015, 10:45:00 PM12/29/15
to Dexie.js

Does Dexie have a lock mechanism and concepts? Or related API?

David Fahlander

unread,
Jan 5, 2016, 6:56:32 AM1/5/16
to Dexie.js
Dexie and IndexedDB by itself has the concept of transactions which means that if you do an operation within a transaction, these operations will be atomic. 

Dexie also have an internal locking mechanism used when simulating sub-transactions that make sure a writeable sub transaction will lock the main transaction such that operations put on the main transaction will be queued until the sub transaction completes.

To accomplish locking, use a transaction:

function addFriendWithPet() {
  return db.transaction('rw', db.friends, db.pets, function () {
    db.friends.add({name: 'Foo'}).then(function (fooId) {
      return db.pets.add({name: 'FoosPet', friendId: fooId});
    });
  });
}

This will guarantee that the friend and its pet is added atomically.

In case this function is called from an already ongoing transaction, Dexie will simulate a sub transaction by locking the main transaction until the sub transaction is done. Example:

db.transaction('rw', db.friends, db.pets, function () {
   addFriendWithPet();
   db.pets.toArray().then(function (pets) {
     console.log(JSON.stringify(pets)); // Will contain the added pet even though we didnt wait for addFriendWithPet() to complete.
   });
});

Don't know if this was the answer to the question or not?
Reply all
Reply to author
Forward
0 new messages