Ad

How To Get Value From Firestore Using Firebase Functions?

I would like to do a very basic request, to get the textvalue of my document 'LA'. I need to retrieve the value before doing others things with it.

async function getValue() {

  doc = await admin.firestore().doc('cities/LA').get();
  console.log('Authorized User Data From Function:', doc.data());
  result = doc.data().text;
  return result;
}

app.get('/hello-world',  async(req, res) => {

  console.log("before" );

  var text = getValue();

  console.log(text);
  //...do something with text

  console.log("after" );

  return res.status(200).send("sent !");

});
module.exports.app = functions.https.onRequest(app);

I have no errors when I deploy.

/Users/user/Documents/APP TEST/functions/index.js
  170:12  warning  Avoid nesting promises          promise/no-nesting
  170:12  warning  Avoid nesting promises          promise/no-nesting
  173:12  warning  Unexpected function expression  prefer-arrow-callback
  180:12  warning  Unexpected function expression  prefer-arrow-callback

✖ 4 problems (0 errors, 4 warnings)
  0 errors and 2 warnings potentially fixable with the `--fix` option.

✔  functions: Finished running predeploy script.
i  functions: ensuring necessary APIs are enabled...
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (42.45 KB) for uploading
✔  functions: functions folder uploaded successfully
i  functions: updating Node.js 8 function app(us-central1)...
i  functions: updating Node.js 8 function sendIAPAnalytics(us-central1)...
✔  scheduler: all necessary APIs are enabled
✔  functions[sendIAPAnalytics(us-central1)]: Successful update operation. 
✔  functions[app(us-central1)]: Successful update operation. 

✔  Deploy complete!

Expected logs:

before
Authorized User Data From Function:
<my text value>
after

Displayed logs:

>Function execution started
>Function execution took 517 ms, finished with status code: 200

and nothing else :(

What's wrong?

I also tried the solution of this post without success, nothing is displayed: https://stackoverflow.com/a/55240125/2123039

Thanks

EDIT 1: No more logs adding try/catch block:

async function getValue() {

  try {
    doc = await admin.firestore().collection('cities').doc("LA").get();
    console.log('Authorized User Data From Function:', doc.data());
    result = doc.data();
    return result;

  } catch(e) {
    console.log(e);
  }

}
Ad

Answer

By doing async function getValue() {...} you are declaring an asynchronous function (which is correct, since the get() function is asynchronous). But then you need to call it as follows

app.get('/hello-world',  async(req, res) => {

  console.log("before" );

  const text = await getValue();   // <- Here use await

  console.log(text);
  //...do something with text

  console.log("after" );

  return res.status(200).send("sent !");

});
Ad
source: stackoverflow.com
Ad