0

I need to maintain unique indexes for firestore transactions. I used "Passing information out of transactions" from https://firebase.google.com/docs/firestore/manage-data/transactions as a guide but have spent 11 hours today trying to get the generated index returned. It is a timing error I am sure but I cannot figure out how to fix it.

Console Log:

returned from call undefined   
eatery-menu.component.ts:200 index 0 event MatCheckboxChange {source: MatCheckbox, checked: true} result true
firebase.service.ts:28 Index= 86
firebase.service.ts:34 newIndex= 87

the eatery-menu.components initiates the call.

orderIndex() {
let db = this.firebase.firestore();
let sfDocRef = db.collection('eOrderIndex').doc('orderIndex');
db.runTransaction(function (transaction) {
  return transaction.get(sfDocRef).
    then(function (sfDoc) {
      if (!sfDoc.exists) {
        throw "Document does not exist!";
      }
      console.log("Index=", sfDoc.data().index);
      let newIndex =  sfDoc.data().index + 1;
      transaction.update(sfDocRef, { index: newIndex });
      return newIndex;
    })
}).then(function (newIndex) {
  console.log("newIndex=", newIndex);
  //return newIndex;       <- tried here 
}).catch(function (err) {
  console.log(err);
});
  //return newIndex;       <- tried here 
}

One of the things that confuse me is that 'return' is use for Promises and returning the result of the function. Sorry I should have put this up tomorrow as it is almost midnight here in Australia so I wont be able to respond until tomorrow morning.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Flashman VC
  • 63
  • 1
  • 7
  • 1
    You can't return a value synchronously from a method doing asynchronous work. You need to learn, understand, and accept asynchronism. Your method must return a Promise (or an Observable). Not an index. There is no workaround around that. You also need to learn about variable scope. Your newIndex variable is defined in the scope of the `function (sfDoc)` function. It's thus not available in any other scope. This rule is basically the same in every programming language. – JB Nizet Mar 03 '18 at 14:07
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Roamer-1888 Mar 03 '18 at 14:56
  • Honestly i worked with promises for sometime & they were a hustle. I would advise you to use observables from RxJs – Isaac Obella Mar 03 '18 at 16:53
  • FYI: You should tag questions about Firebase with the [firebase] tag. – Doug Stevenson Mar 06 '18 at 03:39

0 Answers0