Search code examples
javascriptpromiseindexeddbdexie

Nested promises - IndexedDB transactions using Dexie


I have the following code where the modifying the db item base on an inner promise is not working.

    $('input[type=checkbox][name=checklist]:checked').each(function()
    {
        var collection=db.items.where("name").equals(checkbox.val());
        var success;
        collection.modify(function(item){
             var invokePromise;
                //invokePromise = a fucntion that returns a promise 
                //this invokepromise function needs the item from the db.

             invokePromise.then(function(thirdPartyResponse){
                    item.date=new Date();
                    item.attempts= item.attempts+1; <-- this is not being updated.
            }).catch(function(error){
                    delete this.value; <-- this is also not deleted

            });
        }); 
    });

Solution

  • Considering @David Fahlander answer that Collection.modify() must synchronously update the item, you should collect the async responses first and after alter the database. You can use Promise.all() to asynchronously collect the responses from the invokePromise and modify the database in one go afterwards.