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?