How to get multiple key value from IndexedDb objectstore

与世无争的帅哥 提交于 2019-12-06 04:53:14

Using [1, 2] as you do won't work - that's a key which happens to be an array with two members. Indexed DB currently doesn't understand using lists or sets of keys for querying.

You have a handful of options:

1 - Issue two get requests in parallel. (Since the order is guaranteed, the second request will finish after the first and you know both results will have been returned.)

var results = [];
store.get(1).onsuccess = function(e) {
  results.push(e.target.result);
};
store.get(2).onsuccess = function(e) {
  results.push(e.target.result);

  // results will have the values
};

2 - Use a cursor and a range:

var results = [];
store.openCursor(IDBKeyRange.bound(1, 2)).onsuccess = function(e) {
  var cursor = e.target.result;
  if (cursor) {
    results.push(cursor.value);
    cursor.continue();
  } else {
    // results will have the values
  }
};

3 - Use getAll with a range (newer browsers only - fall back to a cursor if not available)

store.getAll(IDBKeyRange.bound(1, 2)).onsuccess = function(e) {
  // e.target.result will have the entries
};

Note that in options 2 and 3 which use a range you would also get a records with a key of 1.5 if one existed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!