I have factory that's using indexedDB and method getRecipe that needs this indexed db to receive data.
Problem is that indexedDB returns it's instance in asynchronous call and getRecipe is another method that returns it's value in asynchronous call.
I try to solve it via promises, but I failed.
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};
}]);
But this doesent work. In getRecipe the function in then isn't invoked. I don't know where is problem.
request.onsuccess
ever called? – plalx Nov 10 '13 at 14:36then
callback just before callingresolve
. It works right? If it does have a look at what's returned bygetDb()
. – plalx Nov 10 '13 at 14:55request.onsuccess
is actually being called? Your then success function won't execute unless deferred.resolve is actually called. See Maxim Shoustin's answer for more details. – mortalapeman Nov 10 '13 at 17:48