Search code examples
angularasync-awaitangularfire2angular2-observables

Async / Await with AngularFire2 toPromise() method wont work?


I just had a weird problem using AngularFire2 Observables, look at this code and tell me if you have a clue on what is happening :

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});
}

So this code won't work, but if I do it like the next code, it will work :

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}));
}

So how is it possible that creating a promise and resolve the Observable data works while the .toPromise() method won't work ?

Is it a normal behavior ? Am I doing something wrong ? Let me know :-)


Solution

  • The reason why it doesn't work is because your promise is never resolved.

    In order for your promise to be resolved, your observable needs to complete.

    So if you simply prepend the toPromise() with take(1), you'll get the desired effect:

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