I need to iterate IndexedDB table with the Dexie and process each item with some function.
My code is something like that:
var db = new Dexie(dbName);
db.version(dbVersion).stores({
smthtbl: '++id, data, creationTime'});
db.smthtbl.each(function (item) {
return proccessItem(item);
}).then(function() {
console.log("done");
return "done"
});
function proccessItem(item) {
console.log(item.id + " : " + item.data);
};
And I need to set a timeout between iterations so that each next item is displayed through the timeout.
Something like this might work for you.
The iterateWithDelay
function below is reusable for any other case where you want to iterate slowly through an array of items. I also made it pass the index and array in, like .map()
does. (You could also add a feature to stop iteration if the callback returns a certain value like false
, etc.)
Dry-coded, YMMV, etc. :)
const iterateWithDelay = (items, delay, callback) =>
new Promise(resolve => {
let index = 0;
const tick = () => {
const item = items[index];
if (!item) {
resolve();
return;
}
callback(item, index, items);
index++;
setTimeout(tick, delay);
};
tick();
});
var db = new Dexie(dbName);
db.version(dbVersion).stores({ smthtbl: "++id, data, creationTime" });
db.smthtbl
.toArray(items => iterateWithDelay(items, 100, proccessItem))
.then(() => {
console.log("done");
return "done";
});
function proccessItem(item) {
console.log(item.id + " : " + item.data);
}