在PouchDB数据库中,我有一些文档:
{
_id: '765541',
title: 'Mickey Mouse'
},
{
_id: '78910',
title: 'Donald Duck'
}
我正在尝试像这样运行get()
方法:
localCharacter(id: string){
let db = this._db;
let character: any;
console.log('Look for : ' + id + ' in local db');
return new Promise(resolve => {
db.get(id).then((result) => {
console.log('Character: ' + JSON.stringify(result));
character= result.row;
}).catch((error) => {
console.log('Some errors : ' + error);
character = false;
});
console.log('Resolve : ' + character);
resolve(character);
})
}
但是控制台中不断弹出以下消息:
Resolve undefined
注意:我还尝试了以下方法
db.get(id.toString(), {include_docs: true}).then((result)
但同样的事情...
根据 PouchDB get(( API 及其示例响应,需要进行以下修改:
db.get(id).then((result) => {
/* "result.row" is wrong */
//character= result.row;
/* Just do this: */
character= result;
})
正确的解决方法:
localCharacter(id: string){
let db = this._db;
let character: any;
console.log('Look for : ' + id + ' in local db');
return new Promise(resolve => {
db.get(id).then((result) => {
console.log('Character: ' + JSON.stringify(result));
character= result.row;
resolve(character);
}).catch((error) => {
console.log('Some errors : ' + error);
character = false;
resolve(character);
});
})
}
希望对你有帮助...
您甚至可以简化代码:
localCharacter(id: string) {
return this._db.get(id).then(result => result.row).catch(err => false);
}
get
方法本身返回一个承诺,因此无需将其包装到另一个承诺中。