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.

有帮助吗?

解决方案

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).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top