嵌套的承诺 - 使用Dexie IndexedDB的交易

问题描述 投票:2回答:3

我有以下代码,其中在其内承诺修改所述分贝项碱不工作。

    $('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

            });
        }); 
    });
javascript promise indexeddb dexie
3个回答
1
投票

考虑@David Fahlander回答Collection.modify()必须同步更新的项目,你首先应该收集异步响应和改变数据库之后。您可以使用Promise.all()异步收集来自invokePromise的答复,并随后修改一气呵成数据库。


1
投票

Collection.modify()回调必须同步更新的项目。您还可以优化的,而不是equasls的使用查询anyOf()。下面是examplifies另一种策略的例子:

function yourAction () {
  const checkedValues = $('input[type=checkbox][name=checklist]:checked')
    .toArray() // Convert to a standard array of elements
    .map(checkBox => checkBox.value); // Convert to an array of checked values

  return invokePromise.then(thirdPartyResponse => {
    return db.items.where("name").anyOf(checkedValues).modify(item => {
      item.date = new Date();
      ++item.attempts;
    }).catch(error => {
      console.error("Failed to update indexedDB");
      throw error;
    });
  }).catch(error => {
    // Handle an errors from invokePromise
    // If an error occurs, delete the values. Was this your intent?
    console.error("Error occurred. Now deleting values instead", error);
    return db.items.where("name").anyOf(checkedValues).delete();
  });
}

1
投票

你可以检索所有条目,等待的承诺,然后分别对其进行更新:

 (async function() {
   const entries = await db.items
       .where("name").equals(checkbox.val())
       .toArray();

   for(const entry of entries) {
     //...
     await invokePromise;
     await db.items.put(entry);
  }
})();

你可能想用并行和entries.mapPromise.allTable.putAll整个事情。

© www.soinside.com 2019 - 2024. All rights reserved.