2017-06-11 35 views
0

我使用localForage将数据存储为键对象对。我正在使用下面的代码来检索我已经存储的数据。Javascript LocalForage返回长度为null

// Find the number of items in the datastore. 
localforage.length(function(length) { 
    // Loop over each of the items. 
    for (var i = 0; i < length; i++) { 
     // Get the key. 
     localforage.key(i, function(key) { 
      // Retrieve the data. 
       localforage.getItem(key, function(value){ 
        //do stuff 
       }); 
     }); 
    } 
}); 

(我发现了localforage,把上面的代码片段从here

这是行不通的,所以我把console.log()localforage.length()

// Find the number of items in the datastore. 
    localforage.length(function(length) { 
     console.log(length); 
     // Loop over each of the items. 
     for (var i = 0; i < length; i++) { 
      // Get the key. 
      localforage.key(i, function(key) { 
       // Retrieve the data. 
        localforage.getItem(key, function(value) 
         //do stuff 
        }); 
      }); 
     } 
    }); 

原来console.log(length)null ,所以它似乎下面的for循环永远不会被执行。但是在加载网页后,如果我手动localforage.length();在它返回下面的Chrome开发人员工具的控制台类型:

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} 
__proto__:Promise 
[[PromiseStatus]]:"resolved" 
[[PromiseValue]]:2 

这是有道理的,因为我有当前存储2个对象。那么,为什么我的代码片段不工作,为什么长度返回为null?我觉得这与我不熟悉的承诺有关。

回答

0

你是对的,localForage是一个异步API,因此它可以与回调或Promises协同工作。

需要由localforage.length

localforage.length().then(function(length) { .....

这里后使用.then提取自许的价值是。长度的文档,以及:http://localforage.github.io/localForage/#data-api-length

+0

的'。长度()'函数如文件所述,确实允许回调。该API支持任一机制。 – Pointy

+0

@完全是我的想法。 – AZG

+0

但答案确实解决了我的问题。 – AZG