Skip to content

transaction(...).read(...).write(...) returns Promise even tho the types say otherwise #145

@dorklein

Description

@dorklein

Firebase Firestore runTransaction returns a Promise as you can see in the official docs

const cityRef = db.collection('cities').doc('SF');
try {
  //     here 👇
  const res = await db.runTransaction(async t => {
    const doc = await t.get(cityRef);
    const newPopulation = doc.data().population + 1;
    if (newPopulation <= 1000000) {
      await t.update(cityRef, { population: newPopulation });
      return `Population increased to ${newPopulation}`;
    } else {
      throw 'Sorry! Population is too big.';
    }
  });
  console.log('Transaction success', res);
} catch (e) {
  console.log('Transaction failure:', e);
}

But typesaurus types doesn't indicate that the result is a Promise and some transactions might not execute if you exit after the transaction (E.G. in firebase cloud functions, the function might die before the transaction has finished because we didn't await it)

The return type of write in typesaurus is WriteDocsToDocs<WriteResult, Props>

const result = transaction(...).read(...).write((...) => {
  // .... Transaction write ....
  return 'DONE'
}) 

// Typescript -> result: string
// Actual -> 
console.log("result", result)
// result Promise {
//  <pending>,
//...
//},

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions