db.get 如果我第一次调用它不起作用,打字稿

db.get doesn't work if I call it the first time, typescript

我有一个奇怪的问题: 我有一个简单的函数可以从 myData.ts.

中的数据库中获取用户信息
test = <any>{};

  getUserInfoFromPouch(filter: string):any{

    this.db.get(filter).then((result) => {
      this.test = result;
    })
    return this.test;
  }

它的工作原理......有点。

我在我的用户数据页面构造函数中调用该函数:

this.userData = this.myData.getUserInfoFromPouch(this.userId);
console.log('------------------t1----------------------------------');
console.log(this.userData);
console.log('------------------t2----------------------------------');
console.log(this.myData.test);

但我只得到一个 ampty 对象:

------------------t1----------------------------------  main.js:62736:9
Object {  }  main.js:62737:9
------------------t2----------------------------------  main.js:62738:9
Object {  }

如果我通过按钮再次调用该函数,我会得到我期望的实际输出。 如果我不先调用构造函数中的函数,我必须使用两次按钮才能获取数据。 这是非常混乱的。 我尝试了许多不同的函数拼写,例如:

test = <any>{};

      getUserInfoFromPouch(filter: string):any{

        return this.db.get(filter).then((result) => {
        })
      }

test = <any>{};

      getUserInfoFromPouch(filter: string):any{

        this.db.get(filter).then((result) => {
        return result;
      })
      }

我做错了什么? 谢谢你的帮助。

顺便说一句。我在数据库中只有一条记录。 (用于测试目的)

编辑: 好的,我试过这样的功能:

async getUserInfoFromPouch(_id: string){


    try {
      this.test = await this.db.get(_id);
    } catch (err) {
      console.log(err);
    }
    console.log('------------------t3----------------------------------');
    console.log(this.test);

  }

然后我像以前一样在我的用户页面的构造函数中调用该函数。 调用函数后,我用函数中的测试变量填充我的用户数据:

    this.myData.getUserInfoFromPouch("userinfo");
    this.userData = this.myData.test;
    console.log('------------------t1----------------------------------');
    console.log(this.userData);

但是用户数据是空的。我得到了函数的 console.output 之后我做了:

this.userData = this.myData.test; 

我做错了 ;-(

好的,用promises解决了问题。

 this.myData.getDocumentById('userInfo').then(res=>{
      if (res!=undefined){
        this.userData=res;
      } 
    }).catch(err=>{
      console.log('userInfo-error:  ', err)
    }); 

现在可以正常使用了 我的 getDocumentById 函数锁定如下:

 getDocumentById(id: string):any {
    this.syncTwoWay();
    return this.db.get(id).then((doc) => {
      return doc;
    }).catch((err) => {
      console.log('getDocumentById' + err);
    });
  }