简体   繁体   中英

Get pouchdb database info

So I am trying to get the length of a pouchdb database. I am following their api reference to get the length ( https://pouchdb.com/api.html#database_information ). Basically, I have a function which does stuff at the end of that function I want to store the length of the database into a variable.

const db_len_func = this.db.info().then(result => {
  return result['doc_count']
})

const db_len = async() =>{
  this.nextNodeIndex = await db_len_func
}

But when I run this function the this.nextNodeIndex is not getting updated. I want to use this variable inside another function. I am new to promise functions, so any suggestions are appreciated.

This is not a problem with pouchDB rather some confusion about Promises and Async/Await. Either pattern is fine, however choose one - async/await is "modern" - and stick to it; mixing patterns may eventually result in confusing code.

A few problems with the code posted. First, db_len_func

const db_len_func = this.db.info().then(result => {
  return result['doc_count']
})

Is not a function, it is a Promise returned by the invocation of this.db.info() .

As for db_len

const db_len = async() =>{
  this.nextNodeIndex = await db_len_func
}

When db_len is invoked it assigns this.nextNodeIndex to the value of db_len_func which may either be undefined or a promise depending on call order and timing. For what it's worth, the intention surely was await db_len_func() .

This is likely towards your solution.

const db_len_func = async () => { 
   let info = await this.db.info();
   return info['doc_count'];
})

const db_len = async() => {
  this.nextNodeIndex = await db_len_func();
}

// some where, some place, some time....

db_len();

Assuming this is the same object, I would simply do

const updateDocCount = async() => {
   this.nextNodeIndex = await this.db.info().doc_count;
}

nextNodeIndex seems like a mysterious name for what is doc_count IMO.

I recommend reading this blog by Nolan Lawson titled We have a problem with promises .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM