CRUD data in firestore using firebase function onC

2019-09-03 02:42发布

问题:

Nothing happens to my firestore when I call the function below. I also can't see "inside helloWorld" on my GCP logs.

exports.helloWorld = functions.https.onCall((data, context) => {

 console.log("inside helloWorld);
 const users = admin.firestore().collection('users');

 users.doc(data.userId).get().then( // --------------------Line A
    (snapshot) => {
      if (snapshot.exists) {
        console.log("snapshot exists");
        return null;
      } else {
        console.log("inside else");
        users.doc(data.userId).set({
          name: data.name
        });
        return null;
      }
    }
  ).catch(() => 'obligatory catch');

  return; //-----------------------------------------------Line B
});

However, when I place the return on Line A, the function works as expected and a document is created in my firestore. "inside helloWorld" is shown on my GCP logs.

Why is that so? I really appreciate any levels of clarification.

回答1:

According to the documentation for callable functions (particularly the part about sending back a result):

To return data after an asynchronous operation, return a promise. The data returned by the promise is sent back to the client. For example, you could return sanitized text that the callable function wrote to the Realtime Database.

Even if you don't want to send any content in the response, Callable functions still need to respond to the HTTP request that originated them, as all HTTP transactions do.

In either case, you still need to make use of the promises in all your async calls so that Cloud Functions knows when to respond to the client, after all the work is complete. Placing the return statement on "line A" is effectively returning the promise from the async work started by get(), fulfilling this requirement. Without the return statement, Cloud Functions is terminated your function because it thinks there is no more work to complete in order to send the final response.

If you're not familiar about how promises work in JavaScript, watch my video tutorials here: https://firebase.google.com/docs/functions/video-series/