我使用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