Marce
Marce

Reputation: 103

How to obtain the result of a transaction in the Firebase database?

I'm trying to get the result of an update operation on a node of the Firebase Database, working with Angular2. This method is executed in a service class called arbitro.service.ts.

This class has a items attribute, that allows executing get, insertion and update operations on Firebase Database:

items: FirebaseListObservable<any[]>;

The code that was used to perform the update on Arbitro record is shown below:

  editarArbitro(arbitro: Arbitro): void {
    this.items.update(arbitro.id, arbitro);
  }

This method, receives as parameter an instance of Arbitro class and executes the update in the Firebase database.

By analyzing the methods applicable to update operation, I discovered then method. I attach a capture showing the necessary parameters for the then implementation.

then method

The return of the then method is an object of type:

firebase.Promise<any>

As I investigated, this Promise element, returns the code of the result of the transaction on the database.

My question is: is it possible to use this Promise element to know if a transaction ended successfully or failed? How should I handle the return of the update function?

Regards!

Upvotes: 0

Views: 356

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599766

As Doug commented, a Promise can result in two states: either the operation completes successfully, in which case the promise is resolved and its then() callback is called, or the operation fails, in which the promise is rejected and its catch() callback is called.

So you can handle both with:

this.items.update(arbitro.id, arbitro)
    .then(function() {
        console.log("Update completed successfully");
    })
    .catch(function(error) {
        console.log("Update failed: "+error);
    });

Upvotes: 2

Related Questions