我使用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
?我觉得这与我不熟悉的承诺有关。
的'。长度()'函数如文件所述,确实允许回调。该API支持任一机制。 – Pointy
@完全是我的想法。 – AZG
但答案确实解决了我的问题。 – AZG