My factory utilizes indexedDB and a method called getRecipe that relies on this indexed db to fetch data.
The issue arises because indexedDB returns its instance in an asynchronous call, and getRecipe is another method that also returns its value asynchronously.
I attempted to tackle this using promises but unfortunately, I was unsuccessful.
app.factory('RecipesStorage', ['$q', function($q) {
var getDb = function () {
var deferred = $q.defer();
var db;
var request = indexedDB.open('recipes', 1);
request.onupgradeneeded = function (e) {
console.log('Upgrading indexedDb');
var thisDb = e.target.result;
if (!thisDb.objectStoreNames.contains('recipe')) {
thisDb.createObjectStore('recipe');
}
}
request.onsuccess = function (e) {
db = e.target.result;
window.db = db;
deferred.resolve(db);
}
request.onerror = function (e) {
console.error('Error when opening indexedDB');
}
return deferred.promise;
};
var getRecipe = function (recipeId, callback) {
getDb().then(function(db) {
var transaction = db.transaction(['recipe'], 'readonly');
var objectStore = transaction.objectStore('recipe');
var data = objectStore.get(recipeId);
data.onsuccess = function (e) {
var result = e.target.result;
console.log('GetRecipe:', result);
callback(result);
}
data.onerror = function (e) {
console.error('Error retrieving data from indexedDB', e);
}
});
};
return {getRecipe:getRecipe};
}]);
However, the solution didn't work as expected. The function inside the then of getRecipe isn't triggered. I'm unsure about where the problem lies.