I'm attempting to use localforage as the means of storing data, but don't want to rewrite the same code to store and load large arrays of data, so Ive decided to make an object with a prototype which contains said functions. one to setItem and one to getItem. I configure my localforage first, then define my function, then define its prototype.
When I attempt to run this, in the prototype, in setArray, this.forageName is undefined. Why is it undefined, and how do I get it to be recognized?
I want the prototype to recognize when this.forageName is called, it will be called by the instantiated object, and refer to the instantiated object by using 'this'.
localforage.config({
description: 'Storage medium for caching 2d arrays.'
});
/**
* This function is based on Localforage which uses a promise/callback API.
* Promise chains make sure that all values are returned before moving onto the next step.
*
* ForageStorage parses through a 2d array and uses localforage to store each array in key-value pairs,
* where the first item in each sub-array is the key and the entire sub-array is the value.
* @namespace ForageStorage
* @param {string} forageName - The name of the localforage object that this object will instantiate.
* @param {array[]} arrayToStore - The array of arrays to parse through and store.
*/
function ForageStorage(forageName, arrayToStore){
this.forageName = localforage.createInstance({name: forageName});
this.arrayToStore = arrayToStore;
this.retrievedArray = [];
this.promiseArray = [];
};
ForageStorage.prototype = {
setArray: function (){
this.promiseArray = this.arrayToStore.map(function (item) { return this.forageName.setItem(item[0].toString(), item)});
return Promise.all(promiseArray);
},
getArray: function () {
this.forageName.keys()
.then(function (keys) {
this.retrievedArray = keys.map(function (item) {return this.forageName.getItem(item)})
})
return Promise.all(retrievedArray);
},
};
var forageStorage = new ForageStorage("myStorage",textData);
forageStorage.setArray()
.then(forageStorage.getArray())
.then(console.log(param.map(function () { return item.toString(); })));