Here’s a clean and modern way to use IndexedDB with Promises, which makes asynchronous code much easier to read and maintain compared to traditional callback-style.
IndexedDB with Promises – Full Example
This example shows how to:
Open a database
Create an object store (if not exists)
Add records
Get all records
1. Helper Function: Open Database with Schema Setup
function openDatabase(dbName, storeName) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(dbName, 1); // version 1
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName, { keyPath: 'id', autoIncrement: true });
}
};
request.onsuccess = (event) => {
resolve(event.target.result);
};
request.onerror = (event) => {
reject(`DB open error: ${event.target.errorCode}`);
};
});
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Here’s a clean and modern way to use IndexedDB with Promises, which makes asynchronous code much easier to read and maintain compared to traditional callback-style.
IndexedDB with Promises – Full Example
This example shows how to:
1. Helper Function: Open Database with Schema Setup
2. Add a Record
3. Get All Records
4. Putting It All Together
Summary
indexedDBoperations in Promise-based helpers.async/awaitfor cleaner code flow.