因此,我试图获取pouchdb数据库的长度。我遵循他们的api引用来获得长度(信息)。基本上,我有一个函数在函数的末尾填充,我想将数据库的长度存储到一个变量中。
const db_len_func = this.db.info().then(result => {
return result['doc_count']
})
const db_len = async() =>{
this.nextNodeIndex = await db_len_func
}但是当我运行这个函数时,this.nextNodeIndex不会被更新。我想在另一个函数中使用这个变量。我是新承诺的功能,所以任何建议都很感激。
发布于 2022-07-28 22:11:46
这不是pouchDB的问题,而是关于承诺和异步/等待的一些混淆。这两种模式都很好,但是选择一种--异步/等待是“现代的”--并坚持它;混合模式最终可能导致代码混淆。
发布的代码有几个问题。首先,db_len_func
const db_len_func = this.db.info().then(result => {
return result['doc_count']
})不是函数,而是调用this.db.info()返回的承诺。
至于db_len
const db_len = async() =>{
this.nextNodeIndex = await db_len_func
}当调用db_len时,它将this.nextNodeIndex分配给db_len_func的值,该值可能是未定义的,也可能是承诺,具体取决于调用顺序和时间。不管它的价值是什么,变量命名在这里起作用。它的意图似乎是await db_len_func(),但它是有可能的await承诺。
这很可能是你的解决方案。
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();假设this是同一个对象,我只需做
const updateDocCount = async() => {
this.nextNodeIndex = await this.db.info().doc_count;
}nextNodeIndex似乎是doc_count (海事组织)的一个神秘名字。
如果遵守承诺,我强烈建议阅读诺兰·劳森( Nolan )的博客“我们对承诺有异议”。
https://stackoverflow.com/questions/73157559
复制相似问题