Dexie.waitFor()
Since Dexie 2.0
Syntax
Dexie.waitFor(promise, timeout=60000)
Return Value
Description
This method makes it possible execute asynchronous non-indexedDB work while still keeping current context as well as IDB transaction alive.
Keeps IndexedDB transaction alive
When used within a transaction, ongoing transaction will be kept busy until given promise is settled, and that way keeping it alive and prohibit it from automatically being committed.
Keeps observation context alive (liveQuery())
When used within the context of a liveQuery() querier callback, the observation context will be kept after the given promise resolves. In this case, it will not need to keep any transaction alive and does not load the CPU, unless the querier function also performs a transaction.
Use with caution
WARNING: This method can be CPU intensive while waiting for given Promise. It typically triggers about 1000 dummy-queries while waiting for just a 100 milliseconds.
Use with caution when the purpose is to keep a transaction alive as it may put unnecessary CPU load on the browser. A separate task will keep the transaction alive by propagating dummy-requests on the transaction while the given promise is being executed.
However, when used outside a transaction, it will not load the CPU - for example for the purpose of keeping liveQuery context alive and not using it within a transaction
When used for keeping a transaction alive, this method kind of implements an anti-pattern of how not to use indexedDB transactions. On the other hand, it works, is stable across all browsers, and is totally in line with the new indexeddb-promises proposal where this will be possible. So in a future version if the proposal goes live, Dexie will start ride upon that new API if the browser supports it.
Relation to IDBTransaction.waitUntil()
As of current state of the indexeddb-promises proposal, IDBTransaction.waitUntil() will commit the transaction directly after it resolves, while Dexie.waitFor() can be reused several times within the same transaction. This is the reason why we name it differently - to distinguish it from the behavior of IDBTransaction.waitUntil(). If the proposal remains with this behavior, we could still use it to accomplish what we need here, but we would then have to execute the entire scope function using IDBTransaction.waitUntil().
Sample 1
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
await db.transaction('rw', db.friends, async ()=> {
await Dexie.waitFor(sleep(100)); // Sleeps 100 milliseconds
await db.friends.put({id: 1, name: "Ã…ke"});
await Dexie.waitFor(sleep(100)); // Sleeps 100 milliseconds
let theMan = await db.friends.get(1);
alert (`I still got the man: ${theMan.name}`);
});
Sample 1 in plain old ES5 + ES6 Promise
function sleep (ms) {
return new Promise(function (resolve) { setTimeout(resolve, ms); });
}
db.transaction('rw', db.friends, function () {
Dexie.waitFor(sleep(100)).then(function () {
return db.friends.put({id: 1, name: "Ã…ke"});
}).then(function () {
return Dexie.waitFor(sleep(100));
}).then(function () {
return db.friends.get(1);
}).then(function (theMan) {
alert ('I still got the man: ' + theMan.name);
});
})
The above samples shows that you can wait for non-IndexedDB Promises to complete while still keeping transaction alive. You can replace sleep() with WebCrypto calls, fetch() or $.ajax(). When Dexie.waitFor()
resolves it is guaranteed that the transaction will be in an active state and possible to continue working on. Note however that while the given promise is being executed, the transaction may not be guaranteed to be in an active state (may temporarily be inactive), so the operation must NOT involve operations on the transaction. But when the waitFor() promise resolves, the transaction is guaranteed to be in active state again.
await db.transaction('rw', db.friends, async () => {
await Dexie.waitFor(mixedOperations());
async function mixedOperations () {
await sleep(100);
await db.friends.get(1)
.catch('TransactionInactiveError', ex => {
// This will happen!
});
}
await db.friends.get(1); // Will succeed though.
});
What to keep in mind is this:
- Don’t access your own transaction in the operation you wait for using Dexie.waitFor().
- Just access non-IndexedDB work, OR another transaction separate from your own. For example, you MAY start a new top-level transaction or wait on other databases
// We are only locking db.friends initially. But then later in the flow,
// we also lock db.pets to include it as we need it as well.
db.transaction('r', db.friends, () => {
return db.friends.get({name: "Bert"}).then (bert => {
return Dexie.waitFor(db.transaction('r!', db.pets, async () => {
// Locked with exclamation mark ('r!') meaning new top-level transaction.
return db.pets.where({owner: bert.id}).toArray();
})).then(bertsPets => {
bert.pets = bertsPets;
return bert;
});
}).then(bertWithPets => {
// bertWithPets is now a "friend" with a 'pets' property added to it, that
// is an array of the pets that is owned by Bert.
});
});
Behavior of Dexie.waitFor() when not in a transaction
Dexie.waitFor() can also be used when your code is not executing within a transaction. It will then just be equivalent to Promise.resolve(). This can be useful if you write code that does not encapsulate through transaction by itself, but may be encapsulated in a transaction by the caller. By using Dexie.waitFor() you ensure that non-indexedDB operations will keep any existing transaction alive in case caller has encapsulated your code in a transaction.
Table of Contents
- API Reference
- Access Control in Dexie Cloud
- Add demo users
- Add public data
- Authentication in Dexie Cloud
- Best Practices
- Building Addons
- Collection
- Collection.and()
- Collection.clone()
- Collection.count()
- Collection.delete()
- Collection.desc()
- Collection.distinct()
- Collection.each()
- Collection.eachKey()
- Collection.eachPrimaryKey()
- Collection.eachUniqueKey()
- Collection.filter()
- Collection.first()
- Collection.keys()
- Collection.last()
- Collection.limit()
- Collection.modify()
- Collection.offset()
- Collection.or()
- Collection.primaryKeys()
- Collection.raw()
- Collection.reverse()
- Collection.sortBy()
- Collection.toArray()
- Collection.uniqueKeys()
- Collection.until()
- Compound Index
- Consistency in Dexie Cloud
- Consistent add() operator
- Consistent remove() operator
- Consistent replacePrefix() operator
- Consuming Dexie as a module
- Custom Emails in Dexie Cloud
- DBCore
- DBCoreAddRequest
- DBCoreCountRequest
- DBCoreCursor
- DBCoreDeleteRangeRequest
- DBCoreDeleteRequest
- DBCoreGetManyRequest
- DBCoreGetRequest
- DBCoreIndex
- DBCoreKeyRange
- DBCoreMutateRequest
- DBCoreMutateResponse
- DBCoreOpenCursorRequest
- DBCorePutRequest
- DBCoreQuery
- DBCoreQueryRequest
- DBCoreQueryResponse
- DBCoreRangeType
- DBCoreSchema
- DBCoreTable
- DBCoreTableSchema
- DBCoreTransaction
- DBCoreTransactionMode
- DBPermissionSet
- Deprecations
- Derived Work
- Design
- Dexie Cloud API
- Dexie Cloud API Limits
- Dexie Cloud Best Practices
- Dexie Cloud CLI
- Dexie Cloud Docs
- Dexie Cloud REST API
- Dexie Cloud Web Hooks
- Dexie Constructor
- Dexie.AbortError
- Dexie.BulkError
- Dexie.ConstraintError
- Dexie.DataCloneError
- Dexie.DataError
- Dexie.DatabaseClosedError
- Dexie.IncompatiblePromiseError
- Dexie.InternalError
- Dexie.InvalidAccessError
- Dexie.InvalidArgumentError
- Dexie.InvalidStateError
- Dexie.InvalidTableError
- Dexie.MissingAPIError
- Dexie.ModifyError
- Dexie.NoSuchDatabaseErrorError
- Dexie.NotFoundError
- Dexie.Observable
- Dexie.Observable.DatabaseChange
- Dexie.OpenFailedError
- Dexie.PrematureCommitError
- Dexie.QuotaExceededError
- Dexie.ReadOnlyError
- Dexie.SchemaError
- Dexie.SubTransactionError
- Dexie.Syncable
- Dexie.Syncable.IDatabaseChange
- Dexie.Syncable.IPersistentContext
- Dexie.Syncable.ISyncProtocol
- Dexie.Syncable.StatusTexts
- Dexie.Syncable.Statuses
- Dexie.Syncable.registerSyncProtocol()
- Dexie.TimeoutError
- Dexie.TransactionInactiveError
- Dexie.UnknownError
- Dexie.UnsupportedError
- Dexie.UpgradeError()
- Dexie.VersionChangeError
- Dexie.VersionError
- Dexie.[table]
- Dexie.addons
- Dexie.async()
- Dexie.backendDB()
- Dexie.close()
- Dexie.currentTransaction
- Dexie.debug
- Dexie.deepClone()
- Dexie.defineClass()
- Dexie.delByKeyPath()
- Dexie.delete()
- Dexie.derive()
- Dexie.events()
- Dexie.exists()
- Dexie.extend()
- Dexie.fakeAutoComplete()
- Dexie.getByKeyPath()
- Dexie.getDatabaseNames()
- Dexie.hasFailed()
- Dexie.ignoreTransaction()
- Dexie.isOpen()
- Dexie.js
- Dexie.name
- Dexie.on()
- Dexie.on.blocked
- Dexie.on.close
- Dexie.on.error
- Dexie.on.populate
- Dexie.on.populate-(old-version)
- Dexie.on.ready
- Dexie.on.storagemutated
- Dexie.on.versionchange
- Dexie.open()
- Dexie.override()
- Dexie.semVer
- Dexie.setByKeyPath()
- Dexie.shallowClone()
- Dexie.spawn()
- Dexie.table()
- Dexie.tables
- Dexie.transaction()
- Dexie.transaction()-(old-version)
- Dexie.use()
- Dexie.verno
- Dexie.version
- Dexie.version()
- Dexie.vip()
- Dexie.waitFor()
- DexieCloudOptions
- DexieError
- Docs Home
- Download
- EntityTable
- Export and Import Database
- Get started with Dexie in Angular
- Get started with Dexie in React
- Get started with Dexie in Svelte
- Get started with Dexie in Vue
- Hello World
- How To Use the StorageManager API
- Inbound
- IndexSpec
- Indexable Type
- IndexedDB on Safari
- Invite
- Member
- Migrating existing DB to Dexie
- MultiEntry Index
- PersistedSyncState
- Privacy Policy
- Promise
- Promise.PSD
- Promise.catch()
- Promise.finally()
- Promise.on.error
- Promise.onuncatched
- Questions and Answers
- Realm
- Releasing Dexie
- Road Map
- Road Map: Dexie 5.0
- Road Map: Dexie Cloud
- Role
- Run Dexie Cloud on Own Servers
- Sharding and Scalability
- Simplify with yield
- Support Ukraine
- SyncState
- Table
- Table Schema
- Table.add()
- Table.bulkAdd()
- Table.bulkDelete()
- Table.bulkGet()
- Table.bulkPut()
- Table.bulkUpdate()
- Table.clear()
- Table.count()
- Table.defineClass()
- Table.delete()
- Table.each()
- Table.filter()
- Table.get()
- Table.hook('creating')
- Table.hook('deleting')
- Table.hook('reading')
- Table.hook('updating')
- Table.limit()
- Table.mapToClass()
- Table.name
- Table.offset()
- Table.orderBy()
- Table.put()
- Table.reverse()
- Table.schema
- Table.toArray()
- Table.toCollection()
- Table.update()
- Table.where()
- The main limitations of IndexedDB
- Transaction
- Transaction.abort()
- Transaction.on.abort
- Transaction.on.complete
- Transaction.on.error
- Transaction.table()
- Tutorial
- Typescript
- Typescript (old)
- Understanding the basics
- UserLogin
- Version
- Version.stores()
- Version.upgrade()
- WhereClause
- WhereClause.above()
- WhereClause.aboveOrEqual()
- WhereClause.anyOf()
- WhereClause.anyOfIgnoreCase()
- WhereClause.below()
- WhereClause.belowOrEqual()
- WhereClause.between()
- WhereClause.equals()
- WhereClause.equalsIgnoreCase()
- WhereClause.inAnyRange()
- WhereClause.noneOf()
- WhereClause.notEqual()
- WhereClause.startsWith()
- WhereClause.startsWithAnyOf()
- WhereClause.startsWithAnyOfIgnoreCase()
- WhereClause.startsWithIgnoreCase()
- db.cloud.configure()
- db.cloud.currentUser
- db.cloud.currentUserId
- db.cloud.events.syncComplete
- db.cloud.invites
- db.cloud.login()
- db.cloud.logout()
- db.cloud.options
- db.cloud.permissions()
- db.cloud.persistedSyncState
- db.cloud.roles
- db.cloud.schema
- db.cloud.sync()
- db.cloud.syncState
- db.cloud.userInteraction
- db.cloud.usingServiceWorker
- db.cloud.version
- db.cloud.webSocketStatus
- db.members
- db.realms
- db.roles
- db.syncable.connect()
- db.syncable.delete()
- db.syncable.disconnect()
- db.syncable.getOptions()
- db.syncable.getStatus()
- db.syncable.list()
- db.syncable.on('statusChanged')
- db.syncable.setFilter()
- dexie-cloud-addon
- dexie-react-hooks
- liveQuery()
- unhandledrejection-event
- useLiveQuery()
- useObservable()
- usePermissions()