Javascript LocalForage 返回长度为 null
Javascript LocalForage returning length as null
我正在使用 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
});
});
}
});
(我发现了 localforage,并从 here 中获取了上面的代码片段。)
这行不通,所以我在 localforage.length()
之后放了 console.log()
// 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();
加载网页后,它会 returns 以下内容:
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
__proto__:Promise
[[PromiseStatus]]:"resolved"
[[PromiseValue]]:2
这是有道理的,因为我目前存储了 2 个对象。那么为什么我的代码片段不起作用,为什么长度返回为 null
?我觉得这和我不熟悉的promises有关。
你是对的,localForage 是一个异步的 API,所以它要么与回调一起工作,要么与 Promises 一起工作。
您需要在 localforage.length
之后使用 .then
从承诺中提取值
localforage.length().then(function(length) { .....
这里还有 .length 的文档:http://localforage.github.io/localForage/#data-api-length
我正在使用 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
});
});
}
});
(我发现了 localforage,并从 here 中获取了上面的代码片段。)
这行不通,所以我在 localforage.length()
console.log()
// 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();
加载网页后,它会 returns 以下内容:
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
__proto__:Promise
[[PromiseStatus]]:"resolved"
[[PromiseValue]]:2
这是有道理的,因为我目前存储了 2 个对象。那么为什么我的代码片段不起作用,为什么长度返回为 null
?我觉得这和我不熟悉的promises有关。
你是对的,localForage 是一个异步的 API,所以它要么与回调一起工作,要么与 Promises 一起工作。
您需要在 localforage.length
.then
从承诺中提取值
localforage.length().then(function(length) { .....
这里还有 .length 的文档:http://localforage.github.io/localForage/#data-api-length