You're viewing the legacy docs. They are deprecated as of May 18, 2016.
These docs are for version 2.4.2 and below of the Javascript SDK. Go to our current docs, or see our Web migration guide.

Version 2.4.2Changelog

Firebase.transaction()

Atomically modify the data at this location. Unlike a normal set(), which just overwrites the data regardless of its previous value, transaction() is used to modify the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.

To accomplish this, you pass transaction() an update function which is used to transform the current value into a new value. If another client writes to the location before your new value is successfully written, your update function will be called again with the new current value, and the write will be retried. This will happen repeatedly until your write succeeds without conflict or you abort the transaction by not returning a value from your update function.

If provided, your onComplete callback will be called asynchronously after the transaction has finished.

Transactions are useful for "atomic operations", such as atomically incrementing a value. See Transactions for more details.

Note that modifying data with set() will cancel any pending transactions at that location, so extreme care should be taken if mixing set() and transaction() to update the same data.

Note: When using transactions with Security and Firebase Rules in place, be aware that a client needs .read access in addition to .write access in order to perform a transaction. This is because the client-side nature of transactions requires the client to read the data in order to transactionally update it.

// Increment Fred's rank by 1.
var fredRankRef = new Firebase('https://docs-examples.firebaseio.com/samplechat/users/fred/rank');

fredRankRef.transaction(function(currentRank) {
   // If /users/fred/rank has never been set, currentRank will be null.
  return currentRank+1;
});
// Try to create a user for wilma, but only if the user id 'wilma' isn't already taken
var wilmaRef = new Firebase('https://docs-examples.firebaseio.com/samplechat/users/wilma');

wilmaRef.transaction(function(currentData) {
  if (currentData === null) {
    return { name: { first: 'Wilma', last: 'Flintstone' } };
  } else {
    console.log('User wilma already exists.');
    return; // Abort the transaction.
  }
}, function(error, committed, snapshot) {
  if (error) {
    console.log('Transaction failed abnormally!', error);
  } else if (!committed) {
    console.log('We aborted the transaction (because wilma already exists).');
  } else {
    console.log('User wilma added!');
  }
  console.log("Wilma's data: ", snapshot.val());
});