Search code examples
angularpromiseindexeddbdexie

Promises Angular Dexie(indexedDB)


I'm new to Angular, Dexie(indexedDB) and Promises, so pls be kind.

I have some data in my db, to keep it simply and self explanatory lets say every entry saves id, (dogName) and dogBreed.

I want do do something like:

if (id === 1) {
    // add some data
}else {
    // add some other data

but if I do someting like:

db.list.get({id: 1}, temp => this.entry = temp);

then I could use it in my HTML but in my ts-file it's still undefined. So I tried to do it with promises, and thats what I came up with so far:

db.list.where('id').equals(1).first().then(function() {
    // add some data 
}).catch(function() {
    // add some other data
});

I hoped, that if theres no entry with id = 1, that it would enter catch, but it doesn´t. I guess I have to do something with resolve and reject, but by now I don't understand them so far that I could use them.

Does anyone have an idea how to solve this?


Solution

  • If the result is not found, the promise returned from db.list.where('id').equals(1).first() will resolve with the value undefined and not reject.

    So you should basically do:

    db.list.where('id').equals(1).first().then(function(item) {
        if (item) {
            // add some data 
        } else {
            // add some other data
        }
    }).catch(function(error) {
        // log or show the error
    });