我使用localForage将数据存储为密钥-对象对。我使用下面的代码检索我已经存储的数据。
// 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
});
});
}
});(我发现了关于本地牧草的信息,并从这里获取了上面的代码片段。)
这不起作用,所以我把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循环似乎从未被执行过。但是,在加载网页之后,如果我手动在Chrome工具控制台中输入localforage.length();,它将返回以下内容:
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
__proto__:Promise
[[PromiseStatus]]:"resolved"
[[PromiseValue]]:2这是有意义的,因为我有两个对象存储在当前。那么,为什么我的代码片段不能工作,为什么长度作为null返回?我觉得这与我不熟悉的承诺有关。
发布于 2017-06-11 14:04:52
您是对的,localForage是一个异步API,所以它可以用于回调或承诺。
您需要在.then之后使用localforage.length从承诺中提取值。
localforage.length().then(function(length) { .....
下面也是.length的文档:http://localforage.github.io/localForage/#data-api-length
https://stackoverflow.com/questions/44484695
复制相似问题