Have a look at this section of the documentation on Cloud Functions, which explains why it is "important to manage the lifecycle of a function to ensure that it resolves properly".
If you want to be sure that "the Cloud Functions instance running your Cloud Function (CF) does not shut down before your CF successfully reaches its terminating condition or state" (in your case, when the asynchronous work is done), you need to "resolve your CF by returning a JavaScript promise".
So, if you don't do that, there is the risk that the Cloud Functions instance running your CF shuts down before your calls to one or more async functions complete.
However, it does NOT mean that this will always happen. It may be very well possible that the Cloud Functions instance running your CF continues to run after you sent back the response to the client (with res.end();
) resulting in the async work being completed.
The problem is that this is totally out of your control (it depends on how the Cloud Functions platform manages you Cloud Function instances): sometimes it may continue running (completing the async work), sometimes it may not.
You will find a lot of questions on Cloud Functions on Stack Overflow which explain that their problem is that the Cloud Function sometimes executes the async work correctly and sometimes not: the reason is simply because they don't return the Promises returned by the async calls.
Does this affect usage?
Yes, as clearly said in the doc: "By terminating functions correctly, you can avoid excessive charges from functions that run for too long or loop infinitely."
So, concretely, in your case you should do something like:
exports.action = functions.https.onRequest(async (req, res) => { // <-- Note the async keyword here
await admin.database().ref('action').add({ 1: 2 });
res.end(); // or just `return;` for other functions
});
Note that if your Cloud Function is synchronous (it does not call any asynchronous method) you have to terminate it with a simple return;
statement (or by calling send()
, redirect()
, or end()
for an HTTPS Cloud Function). For example:
exports.action = functions.https.onRequest((req, res) => {
const result = 1 + 3;
res.status(200).send(result);
});
or
exports.unusefulCloudFunction = functions.firestore
.document('users/{userId}').onWrite((change, context) => {
const result = 1 + 3;
console.log(result);
return;
});