0

I am trying to return the document id when I create it. Since Firebase functions are async the return value is not completed until the query is done. How can I prevent this so I can wait to get the value when the query is done?

This function create the document is located in a service:

public makeDoc(title: string, score: number): any{

    const fields = {
      title: title,
      score: number
    }

   this.db.collection('saved').add(fields)
   .then(function(ref) {
     console.log(ref.id);
     return ref.id;
     })

  }

I call this from a function which is located in a component:

onCreate() {
      const str = this.createService.makeDoc(this.title, this.score);
    console.log(str);

}
robsiemb
  • 6,157
  • 7
  • 32
  • 46
  • 2
    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) – traktor Nov 08 '19 at 00:47

2 Answers2

0

Try following:

const fields = {
      title: title,
      score: number
    }


  var newFieldsRef = this.db.collection('saved').push();
  this.db.collection('saved').child(newFieldsRef).set(fields);

  var id = newFieldsRef.toString();
0

You don't want to prevent waiting until the query is done, you should embrace the use of promises here.

First, if you haven't, make sure you import the firestore namespace in the service:

import { firestore } from 'firebase';

Now, for your service:

I had to slightly change your makeDoc method as the fields object wasn't being created in a valid way (e.g. reusing the number type):

public makeDoc(titleParam: string, scoreParam: number): Promise<firestore.DocumentReference> {
  const fields = {
    title: titleParam,
    score: scoreParam
  };

  return this.db.collection('saved').add(fields);
}

This now returns a Promise<DocumentReference> which, when resolved, the reference will point to the created document.

Now, the call to it in onCreate looks like:

onCreate() {
  this.createService.makeDoc('myTitle', 123)
    .then((ref) => { console.log(ref.id); })
    .catch((err) => { console.log(err); });
}

And this will log the id as soon as it is available.

robsiemb
  • 6,157
  • 7
  • 32
  • 46