0

I have a angularJS factory created to insert and get some values from IndexedDB. I can successfully insert the values to the IndexedDB. But when i try to get the values out of the DB and pass it to the controller i face problems.

factory.getAllProgressData = function() {
        var dbOptions = {};
        dbOptions.include_docs = true;

        var output = {};
        var result = {};
        pouchDb.allDocs(dbOptions, function(err, res) {
            if (err)
                console.log(err);
            if(res) {               
                output.weight = getWeightValues(res.rows);  
                console.log(output);    // <== This console line prints the object
            }
        });

        console.log(output);    // <== This console line does NOT print the object
        return output;
};

var getWeightValues = function(rows) {
        var weightValues = [];
        for (var i = 0; i < rows.length; i++) {
            weightValues.push(rows[i].doc.Weight);
        };
        return weightValues;
    };

As you can see in the comments of the code, when i print the object to the console at the first place it prints. But when i try to do it bellow it doesn't print. And the return value is also empty. I'm very new to javascript and this behavior is not clear to me. I want the result object to be returned to the Controller. Please help. Thanks in advance.

Kasun Kodagoda
  • 3,956
  • 5
  • 31
  • 54

1 Answers1

0

Just guessing but maybe the answer is because pouchDb.allDocs is an asynchronous function. This might be a good opportunity for you to learn about writing asynchronous JavaScript (aka AJAX). AJAX is a difficult concept for those new to JavaScript.

For example, you should be able to clearly understand what gets printed to the console and in what order in the following code:

function printB() { console.log('B'); }
console.log('A');
setTimeout(printB, 10);
console.log('C');

The answer is ACB, not ABC, and not BAC. If you understand why, you are well on your way to answering your own question.

A slightly more relevant example:

var a = 'A';
function changeAtoB() { a = 'B'; console.log(a); }
console.log(a);
setTimeout(changeAtoB, 10);
console.log(a);

The answer is AAB, not ABA, for the same reasons as the previous example. In addition, note that setTimeout does a specific thing, but it is a good general introductory example of the concept of an asynchronous function.

To address your question more directly, the second example corresponds to why your output variable is probably defined for one call to console.log but not the other.

Josh
  • 17,834
  • 7
  • 50
  • 68