I'm using localForage to store data as key-object pairs. I'm using the following code to retrieve the data I have already stored.
// 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
});
});
}
});
(I found out about localforage and took the above code snippet from here.)
This was not working, so I put console.log()
after 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
});
});
}
});
Turns out console.log(length)
gives null
, so it seems the for loop beneath it never gets executed. However after loading the webpage if I manually type in localforage.length();
in the Chrome developer tools console it returns the following:
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
__proto__:Promise
[[PromiseStatus]]:"resolved"
[[PromiseValue]]:2
Which makes sense as I have 2 objects stored currently. So why is my code snippet not working and why is length returned as null
? I feel this has something to do with promises which I am unfamiliar with.
You are correct, localForage is an asynchronous API, so it either works with callbacks or Promises.
You need to extract the value from the promise by using .then
after the localforage.length
localforage.length().then(function(length) { .....
Here are the docs for .length as well: http://localforage.github.io/localForage/#data-api-length