0

I have a problem. I need the number of users in the PouchDB database. I'm using the allDocs function and everything is fine here. I want to extract it to the variable amunt. Unfortunately, it does not work in my record. What am I doing wrong? Thanks for the answers.

function numberOfUsersInDb(){
var amount = 0;

db.allDocs({
}).then(function (result) {
    amount = result.total_rows;
    return amount
    }).catch(function (err) {
    console.log(err);
});
return amount; }
Dyboo
  • 21
  • 2
  • Possible duplicate of [How to make an Asynchronous Method return a value?](https://stackoverflow.com/questions/6045343/how-to-make-an-asynchronous-method-return-a-value) – Chirag Ravindra Apr 30 '18 at 10:07
  • The `db.allDocs()` is an async call, so you must wrap your `numberOfUsersInDb` function into a `Promise` or you have to take a callback function to return the `amount` to the caller function. – Sajjad Hossain Apr 30 '18 at 10:09
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam May 08 '18 at 12:39

1 Answers1

1

You can try the following code which returns the amount from then and access it from caller function

function numberOfUsersInDb(){
  var amount = 0;
  return db.allDocs({})
  .then(function (result) {
    amount = result.total_rows;
    return amount;
  }).catch(function (err) {
    console.log(err);
  });
}

function test() {
  numberOfUsersInDb()
  .then(function (amount) {
    console.log('Total user:', amount);
  });
}

test();
Sajjad Hossain
  • 111
  • 1
  • 9