0

I am working with angularjs and chrome app. (Beginner in this scope) I am using idb library of promise for indexedDB. What I want is to get the all categories from store and return them in a controller function. my code look //check for support

     if (!('indexedDB' in window)) {
        console.log('This browser doesn\'t support IndexedDB');
      }

      const dbPromise = idb.open('test-db4', 2, function(upgradeDb) {
          if (!upgradeDb.objectStoreNames.contains('category')) {
              var category = upgradeDb.createObjectStore('category', {keyPath: 'cat_id', autoIncrement: true});
              category.createIndex('cat_name', 'cat_name', {unique: true});
              category.createIndex('cat_addedby', 'cat_addedby', {unique: false});
          }
      }

My Controller and factory Look like this

Factory :

app.factory('database', function(){
    var factory = {};
    factory.allCategories = function(){
        val = [];
        val = dbPromise.then(db => {
            return db.transaction('category')
              .objectStore('category').getAll();
          }).then(function(allObjs){ return allObjs});
          return val;
    }
    return factory;
});

Controller :

 app.controller('catalogController', function($scope, database){
    var cat = database.allCategories().then(function(allobjs){return allobjs});
   console.log(cat);
});

I have tried everything but it still returns the promise not the result of the store which is actually an array. I have searched a lot but I was not able to find any answer which meets this.. Thanks.

anees
  • 1,777
  • 3
  • 17
  • 26
  • 1
    `then` always returns a promise. You need to use a function _inside_ `then` to get at the promise's inner value. Right now, the `then` you have in your controller is completely redundant. – JLRishe May 11 '18 at 05:47
  • 1
    i.e. `database.allCategories().then(console.log)` will log the values you seek – Jaromanda X May 11 '18 at 05:48
  • console.log is printing the array but the problem is that I want to store these values in a golbal variable but I am not able to do it... @JaromandaX – anees May 11 '18 at 05:49
  • @JLRishe Can you please tell me how can that function return that value... – anees May 11 '18 at 05:50
  • at this stage I want a controller function that returns all the categories in an array form... but I am not able to achieve that ... – anees May 11 '18 at 05:51
  • 1
    read the dupe - you need to know how to deal with asynchrony – Jaromanda X May 11 '18 at 05:51

0 Answers0