0

I am adding an empty document to my Firestore collection to get an unique id and then use it. But after "I was called" I get no logs. Why?

async createDocRef() {
  console.log("I was called");
  const x = await this.afStore.collection('feedbacks').add({})
    .then(f => console.log('fulfilled'), uf => console.log('unfulfilled'))
    .catch(() => console.log('error'))
    .finally(() => console.log('finish'));
  console.log('added');
}

But documents are created in collection after running this function

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Alex Teexone
  • 63
  • 1
  • 5

1 Answers1

0

You're mixing async/await and then/catch, by itself it's not bad, but it's confusing and might lead to some unexpected behaviour, this answer explains it better.

Under the hood, async/await is just promises.

That is, when you have some code that looks like:

const result = await myAsyncFunction();    
console.log(result): 

That's exactly the same as writing:

myAsyncFunction().then(data => {    
 const result = data;    
 console.log(result);  
});  

The reason then - that you shouldn't mix async/await and .then chains - is because it's confusing.

It's better to just pick one style, and stick to it.

That said, you can rewritte your function into:

createDocRef() {
  console.log("I was called");
  var afStore = firebase.firestore();
  afStore.collection('feedbacks').add({}) 
    .then(function(docRef) {
       console.log("fulfilled");
     })
    .catch(function(docRef) {
       console.log("error");
     })
    .finally(function(docRef) {
       console.log("finished);
    });
  console.log('added');
}
Emmanuel
  • 1,436
  • 1
  • 11
  • 17