0

I have the following code (db and _db are separate so please dont get confused):

function getValues() {
    let _db = [];

    database
    .init()
    .then(function(db) {

    /* some code that inserts a list of objects into the _db array */

    })
    .finally(function(db) {

    if (db) db.close();

    });

    return _db;
}

The problem is, i always get an empty _db value whenever i call getValues() function. I know its probably something to do with async JS. But please tell me how can i get the final value of _db and not the initialized, empty value of _db.

Devashish
  • 1,260
  • 1
  • 10
  • 21

1 Answers1

0

The reason why _db is always empty is because the call to the database is made asynchronously. Your function terminates before the call completes and returns an empty array.

To handle the asynchronous call you're going to have to return the promise itself which is then handled by the caller

function getValues() {    
    return database
        .init()
        .then(function(db) {

        /* some code that inserts a list of objects into the _db array */

        })
        .finally(function(db) {

        if (db) db.close();

        });
}
tomcek112
  • 1,516
  • 10
  • 16
  • 1
    This is the only answer here that explain what is the problem and why it is a problem before providing a solution. – Stav Alfi Jan 14 '19 at 17:48