Transaction.getAll vs Promise.all in the frontend

Viewed 126

In NodeJS, with the firebase-admin library, when you run a transaction, you can use a function called getAll to read multiple documents, like this:

runTransaction((t) => {
  const docs = await t.getAll(someDocRef, anotherDocRef);
});

Nonetheless, in the frontend you use the Javascript SDK (or a library that wraps it, like @angular/fire in my case), and with it you don't have getAll but get (for one document).

My question is, will I get the same functionality of getAll if I do:

runTransaction((t) => {
  const docs = await Promise.all([
    t.get(someDocRef),
    t.get(anotherDocRef),
  ])
});
1 Answers

There is an important difference in how transactions handle concurrency between the client and admin SDKs:

  1. When using the client SDK, a transaction will keep track of all the documents that are used within it. If any of these documents is edited by an external operation, the transaction will retry from scratch ensuring the latest data is used.

  2. On the other hand, the server/admin SDK will go ahead and place a pessimistic lock on the documents that are used. External operations that try to change the documents used within the transaction will fail, or will not complete until the database lock is lifted.

Besides concurrency control in transactions, if your question is about whether getAll() on the server and a Promise.all() array of get() operations on the client accomplish similar results, then in the code both will return a single promise that resolves to an array of DocumentSnapshot with each document being fetched.

In both cases, your resulting docs constant will simply contain the array of documents after the Promise resolves. I tested this in both SDKs.

// Iterating over documents regardless of which SDK is used in the transaction
myDocs.forEach( myDoc => {
    console.log(myDoc.data());
});

//Output in both SDKs
{ lastName: 'Doe', firstName: 'Jane' }
{ lastName: 'Smith', firstName: 'John' }
{ firstName: 'Foo', lastName: 'Bar' }
Related