【问题标题】:Async / Await with AngularFire2 toPromise() method wont work?Async / Await with AngularFire2 toPromise() 方法不起作用?
【发布时间】:2018-06-09 23:43:17
【问题描述】:

我在使用 AngularFire2 Observables 时遇到了一个奇怪的问题,看看这段代码,告诉我你是否知道发生了什么:

async save(){
 const client = await this.getClient(this.id);
 console.log(client); // ZoneAwarePromise blah blah
}

getClient(clientId) {
 return this.db.object('clients/' + clientId)
            .valueChanges()
            .toPromise()
            .then((client: any) => {key: clientId, name: client.name});
}

所以这段代码不起作用,但如果我像下一个代码那样做,它会起作用:

async save(){
 const client = await this.getClient(this.id);
 console.log(client); // {key: 'blah', name: 'fooblah'}
}

getClient(clientId) {
 return new Promise((resolve, reject) => {
    this.db.object('clients/' + clientId)
            .valueChanges()
            .subscribe((client: any) => resolve({key: clientId, name: client.name}));
}

那么,如何创建 Promise 并解析 Observable 数据而 .toPromise() 方法不起作用?

这是正常行为吗?难道我做错了什么 ?让我知道:-)

【问题讨论】:

  • 嗨,我认为您的问题是 .then((client: any) => {key: clientId, name: client.name});行,因为你正在履行承诺
  • 你好@federicoscamuzzi thx 为你的回答,但如果我不使用 then() 的承诺,我的代码只是在 const client = await this.getClient(this.id); 之后停止即使 console.log(client) 也不会触发:x

标签: angular async-await angularfire2 angular2-observables


【解决方案1】:

它不起作用的原因是你的承诺永远不会解决

为了解决您的承诺,您的 observable 需要 complete

因此,如果您只是在 toPromise() 前面加上 take(1),您将获得所需的效果:

return this.db.object('clients/' + clientId)
              .valueChanges()
              .take(1)
              .toPromise();

【讨论】:

  • 谢谢,我没有测试它,但我相信这是一个很好的答案。谢谢队友:-)
  • 或者,您也可以使用 first() 运算符来代替 take(1),这样更具描述性,更能反映问题
猜你喜欢
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 2020-12-07
  • 2017-09-04
相关资源
最近更新 更多