为什么即使objectStore不包含对象,indexedDB objectStore.get也会成功调用? [英] Why does indexedDB objectStore.get call onsuccess even when the objectStore does not contain the object?

查看:123
本文介绍了为什么即使objectStore不包含对象,indexedDB objectStore.get也会成功调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于indexedDB的一件奇怪的事情是,带有不在对象库中的键的objectStore.get()请求生成的(event.target.results == undefined)事件是成功事件(请参见:

One of the odd things about indexedDB is that a objectStore.get() request with a key that is not in the objectstore generates a success event with (event.target.results == undefined) (see: http://www.w3.org/TR/IndexedDB/#object-store the get function).

我需要捕获这种成功" 并将其记录下来.目前,我在返回的事件中找不到KEY.所以我正在做一个真正的黑客,并将其存储在交易中.有什么建议吗?

I need to trap this type of "success" and log it. Right now, I cannot find the KEY in the returned event. So I am doing a real hack and storing it in the transaction. Any advice?

   var deferred = new jQuery.Deferred(); // this is what gets returned
    var id = view.zoom + "-" + view.tile.column + "-" + view.tile.row;
    trans = DB.transaction(["Images"], "readonly");
    store = trans.objectStore("Images");
    req = store.get(id);
    trans._keyPathForGet = id; // hack
    req.onsuccess = function (e) {
        var blob = e.target.result;
        if (blob == undefined) {
            console.log("no blob of id: " + e.target.transaction._keyPathForGet);
            deferred.resolve(null);
        } else {
            var imgURL = URL.createObjectURL(blob);
            deferred.resolve(imgURL); // let leaflet know we're done, and give it the URL
            URL.revokeObjectURL(imgURL); // not sure if we're revoking it too soon here
        }

推荐答案

这是用于组合键和键范围的超紧凑API设计的产物.您还可以发现删除ramdon键,即使没有删除任何内容,也会获得成功事件.我可以成功返回键范围查询,但是键查询应该返回错误事件.

That is artifact of over-reaching compact API design for combining key and key range. You can also find deleting a ramdon key also get success event even thought nothing was deleted. I am fine with returning success for key range query, but key query should return to error event.

无论如何,对于这类问题有很好的替代解决方案.最好的方法是使用游标.存储密钥不是问题,您可以将其保留在函数闭包之内.

Anyways, there are good alternative solutions for this kind of problems. The best way is using cursor. Storing the key is not a problem, you can keep under a function closure.

var getFile = function (id) {
  ...
  var req = store.openCursor(id);
  req.onsuccess = function(e) {
    var cursor = e.target.result;
    if (cursor) {
       var blob = cursor.value; 
       ...
    } else {
       var err = new Error();
       err.name = 'NotFoundError';
       err.id = id;
       deferred.reject(err);        
    }
  }
  return deferred;
}

您还可以使用count方法查询键是否在对象存储库中.

You can also use count method to query a key is in a object store or not.

这篇关于为什么即使objectStore不包含对象,indexedDB objectStore.get也会成功调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆