0

I don't know why, but for some reasons I have trouble getting data from my indexedDB using PouchDB and storing that data in a variable.

I have a function that fetches all the data from my database, like this:

load_all = function() {
  var database = new PouchDB('ProjectDB');
  var remoteCouch = false;
  database.allDocs({include_docs: true, descending: true}, function(error, doc) {
    if (error) ...
    else {
      if (doc.rows.length > 0) return doc.rows;
      else ...
    }
  });
}

var projects = load_all();
console.log(projects); // will log 'undefined'

I have no idea why it wont, work.

T.Lange
  • 576
  • 1
  • 4
  • 16
  • 1
    I don't have any experience with pouchDB but here are some generic tips that could help out: First check if the function is running at all. I'd guess it's not since you're getting undefined. If not figure out why it's not running, if yes then there's something probably in your conditions. – php_nub_qq Jan 12 '14 at 18:32
  • Since this is an asynchronous task, your return won't work. You can create a callback function that can set the variable projects instead of creating an anonymous function. – Rijvi Rajib Feb 12 '14 at 11:17

1 Answers1

1

Look at line:

      if (doc.rows.length > 0) return doc.rows;

You expect that to return the contents of doc.rows so that your console.log(projects); will display that to you, right? Well, that's not what will happen. The return statement will return from the callback function (function(error, doc) {), not the load_all function. If you want to get at the doc.rows, you need to do it inside the callback function. Like this:

      if (doc.rows.length > 0) console.log(doc.rows);

The reason this is necessary is because IndexedDB is asynchronous. To really understand what that implies and why the code, as you wrote it, cannot work, I recommend you Google for some tutorials about IndexedDB or about asynchronous JavaScript in general (sorry, I don't have any good recommendations off the top of my head).

dumbmatter
  • 9,351
  • 7
  • 41
  • 80