2017-06-11 38 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