Why does my IndexedDB onsuccess response take so much time? - javascript

Indexeddb onsuccess function takes time to execute the lines of code inside it
getAllProjects(callback) {
let self = this;
this.initDatabase(function (db) {
let projects: ProjectdtoService[] = [];
var tx = db.transaction(self.PROJECTS, self.READ_ONLY);
var store = tx.objectStore(self.PROJECTS);
var request = store.openCursor();
request.onsuccess = function (event) {
console.log("response")
var cursor = event.target.result;
if (cursor) {
projects.push(cursor.value.projectObject);
cursor.continue();
} else {
callback(projects);
}
};
})
}
The console log "response" is displayed after a delay of few seconds
As I add more data to the db, and try to retrieve the same from indexeddb onsuccess function, it takes time.
Is there any limitation of indexeddb due which this issue is happening?
any link or documentation for this specific issue?
Any help is appreciated

Related

Get specifics ids in IndexedDB [duplicate]

I want to execute this query
select * from properties where propertyCode IN ("field1", "field2", "field3")
How can I achieve this in IndexedDB
I tried this thing
getData : function (indexName, params, objectStoreName) {
var defer = $q.defer(),
db, transaction, index, cursorRequest, request, objectStore, resultSet, dataList = [];
request = indexedDB.open('test');
request.onsuccess = function (event) {
db = request.result;
transaction = db.transaction(objectStoreName);
objectStore = transaction.objectStore(objectStoreName);
index = objectStore.index(indexName);
cursorRequest = index.openCursor(IDBKeyRange.only(params));
cursorRequest.onsuccess = function () {
resultSet = cursorRequest.result;
if(resultSet){
dataList.push(resultSet.value);
resultSet.continue();
}
else{
console.log(dataList);
defer.resolve(dataList);
}
};
cursorRequest.onerror = function (event) {
console.log('Error while opening cursor');
}
}
request.onerror = function (event) {
console.log('Not able to get access to DB in executeQuery');
}
return defer.promise;
But didn't worked. I tried google but couldn't find exact answer.
If you consider that IN is essentially equivalent to field1 == propertyCode OR field2 == propertyCode, then you could say that IN is just another way of using OR.
IndexedDB cannot do OR (unions) from a single request.
Generally, your only recourse is to do separate requests, then merge them in memory. Generally, this will not have great performance. If you are dealing with a lot of objects, you might want to consider giving up altogether on this approach and thinking of how to avoid such an approach.
Another approach is to iterate over all objects in memory, and then filter those that don't meet your conditions. Again, terrible performance.
Here is a gimmicky hack that might give you decent performance, but it requires some extra work and a tiny bit of storage overhead:
Store an extra field in your objects. For example, plan to use a property named hasPropertyCodeX.
Whenever any of the 3 properties are true (has the right code), set the field (as in, just make it a property of the object, its value is irrelevant).
When none of the 3 properties are true, delete the property from the object.
Whenever the object is modified, update the derived property (set or unset it as appropriate).
Create an index on this derived property in indexedDB.
Open a cursor over the index. Only objects with a property present will appear in the cursor results.
Example for 3rd approach
var request = indexedDB.open(...);
request.onupgradeneeded = upgrade;
function upgrade(event) {
var db = event.target.result;
var store = db.createObjectStore('store', ...);
// Create another index for the special property
var index = store.createIndex('hasPropCodeX', 'hasPropCodeX');
}
function putThing(db, thing) {
// Before storing the thing, secretly update the hasPropCodeX value
// which is derived from the thing's other properties
if(thing.field1 === 'propCode' || thing.field2 === 'propCode' ||
thing.field3 === 'propCode') {
thing.hasPropCodeX = 1;
} else {
delete thing.hasPropCodeX;
}
var tx = db.transaction('store', 'readwrite');
var store = tx.objectStore('store');
store.put(thing);
}
function getThingsWherePropCodeXInAnyof3Fields(db, callback) {
var things = [];
var tx = db.transaction('store');
var store = tx.objectStore('store');
var index = store.index('hasPropCodeX');
var request = index.openCursor();
request.onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
var thing = cursor.value;
things.push(thing);
cursor.continue();
} else {
callback(things);
}
};
request.onerror = function(event) {
console.error(event.target.error);
callback(things);
};
}
// Now that you have an api, here is some example calling code
// Not bothering to promisify it
function getData() {
var request = indexedDB.open(...);
request.onsuccess = function(event) {
var db = event.target.result;
getThingsWherePropCodeXInAnyof3Fields(db, function(things) {
console.log('Got %s things', things.length);
for(let thing of things) {
console.log('Thing', thing);
}
});
};
}

Manipulating data obtained with indexedDB

Im new with IndexedDB and I can not manipulate the data obtained from indexedDB table.I only need do a search values when a button is pressed, then the event activated with the button starts to work and it has to return many results, which may take a few seconds to return values, so I need to use async / await in the callback function. I think the problem is synchronous because I make the callback function async and the function getData() with which I get the data has the word await with it, even so, I can not work with the data, because when I do the console.log(x) it returns the undefined value.
let db;
let request = window.indexedDB.open("Cities", 1);
request.onerror = function (event) {
console.log("error")
};
request.onsuccess = function (event) {
db = event.target.result;
document.getElementById('search').addEventListener('click', async function () {
let x = await getData();
console.log(x)
})
};
function getData() {
let transaction = db.transaction(["City"], "readwrite");
transaction.oncomplete = function (event) {
document.querySelector('body').innerHTML += '<li>Transaction completed.</li>';
};
transaction.onerror = function () {
document.querySelector('body').innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>';
};
let objectStore = transaction.objectStore("City");
let objectStoreRequest = objectStore.getAll();
objectStoreRequest.onsuccess = function () {
document.querySelector('body').innerHTML += '<li>Request successful.</li>';
let myRecord;
return myRecord = objectStoreRequest.result;
};
Of course, the console.log(x) is only to check that the data obtained is correct, once that point would come the part of the search but that is another story.
I'm not sure if my problem is with async / await or because I do not get the IndexedDB data correctly. Any help?
EDIT: -- I think I have found a solution, even though I think it is not the best way to solve the problem. I have moved all the code of the function getData() within the function that invokes the event, once the data is obtained I work within the method .onsuccess of objectStoreRequest, thus I avoid having to use async / await, I also continue working on the transaction which has not yet been finalized. If someone knows a cleaner way to make it work or explain to me why the original post code does not work, I would be very grateful.
I attach the code with which I am currently working:
let db;
let request = window.indexedDB.open("Cities", 1);
request.onerror = function (event) {
console.log("error")
};
request.onsuccess = function (event) {
db = event.target.result;
document.getElementById('search').addEventListener('click',function () {
let transaction = db.transaction(["City"], "readwrite");
transaction.oncomplete = function () {
document.querySelector('body').innerHTML += '<li>Transaction completed.</li>';
};
transaction.onerror = function (event) {
document.querySelector('body').innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>';
};
let objectStore = transaction.objectStore("City");
let objectStoreRequest = objectStore.getAll();
objectStoreRequest.onsuccess = function () {
document.querySelector('body').innerHTML += '<li>Request successful.</li>';
let myRecord;
myRecord = objectStoreRequest.result;
console.log(myRecord)
}
})
};
Anyway it seems like no one have another way for resolve this, so Im go to respond myself this post with this response.
This is the only way I have found to solve the problem, although it seems like a dirty code, I think it could be improved.
let db;
let request = window.indexedDB.open("Cities", 1);
request.onerror = function (event) {
console.log("error")
};
request.onsuccess = function (event) {
db = event.target.result;
document.getElementById('search').addEventListener('click',function () {
let transaction = db.transaction(["City"], "readwrite");
transaction.oncomplete = function () {
document.querySelector('body').innerHTML += '<li>Transaction completed.</li>';
};
transaction.onerror = function (event) {
document.querySelector('body').innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>';
};
let objectStore = transaction.objectStore("City");
let objectStoreRequest = objectStore.getAll();
objectStoreRequest.onsuccess = function () {
document.querySelector('body').innerHTML += '<li>Request successful.</li>';
let myRecord;
myRecord = objectStoreRequest.result;
console.log(myRecord)
}
})
};

Use of indexedDB returns 'undefined'

I'm trying to use indexedDB.
Some parts of my code works.
In the following example, the first function adds server in my DB, however in Chrome debug console there is an undefined message not related to any line. The server is already added though.
The second function puts records in an array, there is also an undefined message not related to any line.
If I do a console.log(servers); just before return servers; I can see the array content, however if I call the function somewhere else in my code, the returned object is undefined.
var dbName = 'myDBname',
dbServersStoreName = 'servers',
dbVersion = 1,
openDBforCreation = indexedDB.open(dbName, dbVersion);
openDBforCreation.onupgradeneeded = function(e) {
var db = e.target.result;
var objStore = db.createObjectStore(dbServersStoreName, { keyPath: "alias"
});
var index = objStore.createIndex("serversAlias", ["alias"]);
};
function addServerInDB(serverAlias,serverAddress,user,pwd){
var myDB = indexedDB.open(dbName, dbVersion);
myDB.onerror = function() {
var notification = document.querySelector('.mdl-js-snackbar');
notification.MaterialSnackbar.showSnackbar(
{message: 'Error while trying to access internal database'});
}
myDB.onsuccess = function(e) {
var db = e.target.result,
request = db.transaction([dbServersStoreName],
"readwrite").objectStore("servers")
.put({alias:''+serverAlias+'',
address:''+serverAddress+'', login:''+user+'',
passwd:''+pwd+''});
request.onsuccess = function(){
var notification = document.querySelector('.mdl-js-snackbar');
notification.MaterialSnackbar.showSnackbar(
{message: 'Server added'});
}
}
};
function listServersInDB(){
var myDB= indexedDB.open(dbName, dbVersion);
myDB.onerror = function() {
var notification = document.querySelector('.mdl-js-snackbar');
notification.MaterialSnackbar.showSnackbar(
{message: 'Error while trying to access internal database'});
}
myDB.onsuccess = function(e) {
var servers = new Array(),
db = e.target.result,
request = db.transaction(["servers"], "readwrite")
.objectStore("servers")
.openCursor();
request.onsuccess = function(e){
var cursor = e.target.result;
if(cursor){
servers.push(cursor.value);
cursor.continue();
}
return servers;
}
}
};
I do not understand where this undefined comes from and if that is why the listServersInDB() function doesn't work.
You need to learn more about how to write asynchronous Javascript. There are too many errors in your code to even begin reasoning about the problem.
Briefly, don't do this:
function open() {
var openDatabaseRequest = ...;
}
openDatabaseRequest.foo = ...;
Instead, do this:
function open() {
var openDatabaseRequest = ...;
openDatabaseRequest.foo = ...;
}
Next, you don't need to try and open the same database multiple times. Why are you calling indexedDB.open twice? You can open a database to both install it and to start using it immediately. All using the same connection.
Next, I'd advise you don't name the database open request as 'myDB'. This is misleading. This is an IDBRequest object, and more specifically, an IDBOpenRequest object. A request isn't a database.
Next, you cannot return the servers array from the request.onsuccess at the end. For one this returns to nowhere and might be source of undefined. Two this returns every single time the cursor is advanced, so it makes no sense at all to return return servers multiple times. Three is that this returns too early, because it cannot return until all servers enumerated. To properly return you need to wait until all servers listed. This means using an asynchronous code pattern. For example, here is how you would do it with a callback:
function listServers(db, callbackFunction) {
var servers = [];
var tx = db.transaction(...);
var store = tx.objectStore(...);
var request = store.openCursor();
request.onsuccess = function() {
var cursor = request.result;
if(cursor) {
servers.push(cursor.value);
cursor.continue();
}
};
tx.oncomplete = function() {
callbackFunction(servers);
};
return 'Requested servers to be loaded ... eventually callback will happen';
}
function connectAndList() {
var request = indexedDB.open(...);
request.onsuccess = function() {
var db = request.result;
listServers(db, onServersListed);
};
}
function onServersListed(servers) {
console.log('Loaded servers array from db:', servers);
}
When you call a function that does not return a value, it returns undefined. All functions in JavaScript return undefined unless you explicitly return something else.
When you call a function from the devtools console, and that function returns undefined, then the console prints out '-> undefined'. This is an ordinary aspect of using the console.
If you want to get a function that returns the list of servers as an array, well, you cannot. The only way to do that in a pretend sort of way, is to use an 'async' function, together with promises.
async function getServers() {
var db = await new Promise(resolve => {
var request = indexedDB.open(...);
request.onsuccess = () => resolve(request.result);
});
var servers = await new Promise(resolve => {
var tx = db.transaction(...);
var request = tx.objectStore(...).getAll();
request.onsuccess = () => resolve(request.result);
});
return servers;
}
One more edit, if you want to call this from the console, use await getServers();. If you do not use the top-level await in console, then you will get the typical return value of async function which is a Promise object. To turn a promise into its return value you must await it.
Clear and helpfull explanations, Thank you.
I open database multiple times beacause the first time is for checking if DB needs an upgrade and doing something if needed. I'll add 'db.close()' in each functions.
Then, I tried your exemple and the result is the same:
console.log('Loaded servers array from db:', servers); works
but return servers; Don't work.
And in console there is already an undefined without related line :
Screenshot

Global variable only accessible to first function?

I have an OK understanding of JS but am ultimately still learning. I'm trying to recreate a PHP/mySQL project over to IndexedDB and can't work out why I'm seeing an error here.
The IndexedDB connection works as expected. The first function (createItem) functions fine, however the second function (getItems) is returning an error claiming that the "db" variable is undefined. It's a global variable so should be accessible by the function's scope, and the createItem function has no problem using it. Can anyone help me see what I've missed here.
// GLOBAL DB VAR
var db;
// WAIT FOR DOM
document.addEventListener("DOMContentLoaded", function(){
// IF INDEXED DB CAPABLE
if("indexedDB" in window) {
// OPEN DB
var openRequest = indexedDB.open("newTabTest",1);
// CREATE NEW / UPDATE
openRequest.onupgradeneeded = function(e) {
// Notify user here: creating database (first time use)
var thisDB = e.target.result;
// Create "items" table if it doesn't already exist
if(!thisDB.objectStoreNames.contains("items")) {
var store = thisDB.createObjectStore("items", {keyPath: "id", autoIncrement: true});
store.createIndex("name","name", {unique:true});
store.createIndex("folder","folder", {unique:false});
store.createIndex("dial","dial", {unique:false});
}
}
openRequest.onsuccess = function(e) {
// Success- set db to target result.
db = e.target.result;
}
openRequest.onerror = function(e) {
// DB ERROR :-(
}
}
},false);
// CREATE ITEM FUNCTION
function createItem(n,u,f,c) {
var transaction = db.transaction(["items"],"readwrite");
var store = transaction.objectStore("items");
var item = {
name: n,
url: u,
folder: f,
colour: c,
dial: 0,
order: 100
}
var request = store.add(item);
request.onerror = function(e) {
console.log("An error occured.");
}
request.onsuccess = function(e) {
console.log("Successfully added.")
}
};
// GET ITEM(S) FUNCTION
// Specify index and key value OR omit for all
function getItems(callback, ind, key) {
var transaction = db.transaction(["items"],"readonly");
var store = transaction.objectStore("items");
var response = [];
// If args are omitted - grab all items
if(!ind | !key) {
var cursor = store.openCursor();
cursor.onsuccess = function(e) {
var res = e.target.result;
if(res) {
var r = {
"name": res.value['name'],
"url": res.value['url'],
"folder": res.value['folder'],
"colour": res.value['colour'],
"dial": res.value['dial'],
"order": res.value['order']
};
response.push(r);
res.continue();
}
}
cursor.oncomplete = function() {
callback(response);
}
} else {
// If both args are specified query specified index
store = store.index(ind);
var range = IDBKeyRange.bound(key, key);
store.openCursor(range).onsuccess = function(e) {
var res = e.target.result;
if(res) {
var r = {
"name": res.value['name'],
"url": res.value['url'],
"folder": res.value['folder'],
"colour": res.value['colour'],
"dial": res.value['dial'],
"order": res.value['order']
};
response.push(r);
res.continue();
}
}
cursor.oncomplete = function() {
callback(response);
}
}
};
As you've figured out in comments, you do have to stick the db-dependent actions inside a function called from a success handler.
This callback-based programming quickly becomes a pain, and a common solution for that is to use promises.
However, making IndexedDB work with promises is still work-in-progress (see https://github.com/inexorabletash/indexeddb-promises if you're interested).
If your goal is to get something done (and not to learn the bare IndexedDB APIs), perhaps you'd be better off finding a wrapper library for IndexedDB (can't recommend one though, since I've not tried working seriously with IDB yet).
I would not recommend using a variable like 'db' as you have in your example. If you are new to reading and writing asynchronous Javascript, you are just going to cause yourself a lot of pain. There are better ways to do it. It takes several pages to explain and is explained in many other questions on StackOverflow, so instead, very briefly, consider rewriting your code to do something like the following:
function createItem(db, ...) {
var tx = db.transaction(...);
// ...
}
function openIndexedDBThenCreateItem(...) {
var openRequest = indexedDB.open(...);
openRequest.onsuccess = function(event) {
var db = event.target.result;
createItem(db, ...);
};
}
function getItems(db, callback, ...) {
var tx = db.transaction(...);
var items = [];
tx.oncomplete = function(event) {
callback(items);
};
// ...
var request = store.openCursor(...);
request.onsuccess = function(event) {
var request = event.target;
var cursor = event.target.result;
if(cursor) {
var item = cursor.value;
items.push(item);
cursor.continue();
}
};
}
function openIndexedDBThenGetItems(db, callback, ...) {
var openRequest = indexedDB.open(...);
openRequest.onsuccess = function(event) {
var db = event.target.result;
getItems(db, callback, ...);
};
}
Also, you don't need to wait for DOMContentLoaded to start using indexedDB. It is immediately available.
If you get the above code, then you can consider a further improvement of adding a simple helper function:
function openIndexedDB(callback) {
var openRequest = indexedDB.open(...);
openRequest.onerror = callback;
openRequest.onsuccess = callback;
}
And then rewrite the examples like this:
function openIndexedDBThenCreateItem(...) {
openIndexedDB(function onOpen(event) {
if(event.type !== 'success') {
console.error(event);
} else {
var db = event.target.result;
createItem(db, ...);
}
});
}
function openIndexedDBThenGetItems(...) {
openIndexedDB(function onOpen(event) {
if(event.type !== 'success') {
console.error(event);
} else {
var db = event.target.result;
getItems(db, ...);
}
});
}

Javascript private variable param update

Resume of the question: how to save internally the params of a function call so it can be use in the next call
I know my problem is not that complicated but I'm kinda confused here.
Here is the problem:
Updateorderbook is a function that connect to a websocket, subscribing to a channel. This function needs to unsubscribe the current channel when it's called for the second time (or more) before to connect to the new channel.
To unsubscribe I need the "previousparams", so what I tried to do is to stock those params in this.currentParams but obviously it's not working.
To resume my problem I need to save internally the params of the call so i can access it on the next call.
updateOrderbook: function(params) {
var self = this;
var ws = OrderbookSocket.getInstance();
if(ws.readyState === 1) {
var request = OrderbookRequest.request(this.currentParams, 'unsubscribe');
ws.send(request);
// this.currentParams = params;
}
ws.onopen = function(e) {
var request = OrderbookRequest.request(params,'subscribe');
self.currentParams = params;
ws.send(request);
}
ws.onclose = function(e) {
console.log(" WS has been closed: ",e);
}
ws.onmessage = function(e) {
}
}
What I don't udnerstand is taht this.currentParams is automatically updated even is ws.onopen is not called! (it's like binded there is something I don't get here).
The problem is that variables are passed by valu and objects by reference, so you need to clone your object, using _.clone() underscore function for example
If this is the Only Thing you want, you can just Change your code to:
var gl_params;
updateOrderbook: function(params) {
// gl_params still your old params
// params are your new params
var self = this;
var ws = OrderbookSocket.getInstance();
if(ws.readyState === 1) {
var request = OrderbookRequest.request(gl_params, 'unsubscribe');
ws.send(request);
}
ws.onopen = function(e) {
var request = OrderbookRequest.request(params,'subscribe');
gl_params = _.clone(params);
ws.send(request);
}
ws.onclose = function(e) {
console.log(" WS has been closed: ",e);
}
ws.onmessage = function(e) {
}
}

Categories