Pier Pier - 3 months ago 52x
Javascript Question

how to chain multiple promises into a single transaction in Firebase

A few months back Firebase implemented promises in the database.

In that blog post there is an example of using a single transaction with promises:

var article;
var articleRef = ref.child('blogposts').child(id);
articleRef.once('value').then(function(snapshot) {
article = snapshot.val();
return articleRef.child('readCount').transaction(function(current) {
return (current || 0) + 1;
}).then(function(readCountTxn) {
article: article,
readCount: readCountTxn.snapshot.val()
}, function(error) {

Is it possible to chain multiple promises into a single transaction to be able to erase data only if everything can be erased?


Do you actually need a transaction or just an atomic operation? You can execute atomic operations on multiple paths simultaneously that will fail if something goes wrong with one of them (ie erase which is a write operation):

var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");

var updatedUserData = {};
updatedUserData["user/posts/location1"] = null;
updatedUserData["user/blogs/location2"] = null;
// Do a deep-path update
ref.update(updatedUserData).then(function() {
}, function(error) {
    console.log("Error updating data:", error);

More info here