Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: Transaction with async/await

I'm trying to use async/await with transaction. But getting error "Argument "updateFunction" is not a valid function."

var docRef = admin.firestore().collection("docs").doc(docId);
let transaction = admin.firestore().runTransaction();
let doc = await transaction.get(docRef);

if (!doc.exists) {throw ("doc not found");}
var newLikes = doc.data().likes + 1;

await transaction.update(docRef, { likes: newLikes });
like image 735
rendom Avatar asked Apr 04 '18 06:04

rendom


2 Answers

The above did not work for me and resulted in this error: "[Error: Every document read in a transaction must also be written.]".

The below code makes use of async/await and works fine.

try{
   await db.runTransaction(async transaction => {
       const doc = await transaction.get(ref);
       if(!doc.exists){
            throw "Document does not exist";
       }
       const newCount = doc.data().count + 1;
       transaction.update(ref, {
           count: newCount,
       });
  })
} catch(e){
   console.log('transaction failed', e);
}
like image 64
alsky Avatar answered Nov 04 '22 19:11

alsky


If you look at the docs you see that the function passed to runTransaction is a function returning a promise (the result of transaction.get().then()). Since an async function is just a function returning a promise you might as well write db.runTransaction(async transaction => {})

You only need to return something from this function if you want to pass data out of the transaction. For example if you only perform updates you won't return anything. Also note that the update function returns the transaction itself so you can chain them:

try {
    await db.runTransaction(async transaction => {
      transaction
        .update(
          db.collection("col1").doc(id1),
          dataFor1
        )
        .update(
          db.collection("col2").doc(id2),
          dataFor2
        );
    });
  } catch (err) {
    throw new Error(`Failed transaction: ${err.message}`);
  }
like image 6
Thijs Koerselman Avatar answered Nov 04 '22 20:11

Thijs Koerselman