Get async value from firestore

前端 未结 3 1161
无人及你
无人及你 2021-01-06 15:35

I am struggling with async operations. I am trying to simply get a value from firestore and storing it in a var.

I manage to receive the value, I can even save it in

3条回答
  •  孤城傲影
    2021-01-06 16:32

    Since getValues function returns a promise, you need to await getValues function while calling it.

    Change getValues like so -

    function getValues(collectionName, docName,) {
      console.log("start")
      var result;
      return db.collection(collectionName).doc(docName).get()
        .then(function (doc) {
          if (doc.exists) {
            console.log("Document data:", doc.data());
            result = doc.data().text;
            console.log(result);
            return result;
          } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
            result = "No such document!";
            return result;
          }
        }).catch (function (err) {
          console.log('Error getting documents', err);
        });
      };

    Then use getValues like so -

    helpMessage = await getValues('configuration','helpMessage');
    

    Explanation -

    async, await are just syntactic sugar for Promises. async functions return a promise (or AsyncFunction more accurately) which needs to be resolved to use its enclosed value.

    See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

提交回复
热议问题