Reputation: 270
Let's say I have a function hello
written like this:
const functions = require("firebase-functions");
const wait3secs = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('3 secs job complete');
resolve('done 3 secs');
}, 3000);
});
}
const wait2secs = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('2 secs job complete');
resolve('done 2 secs');
}, 2000);
});
}
exports.hello = functions.https.onRequest((req, res) => {
wait3secs(); // Unhandled, this uses 3 seconds to complete.
return wait2secs().then(data => {
res.send(data); // Send response after 2 secs.
});
});
The question is: For the above implementation, did I write it correctly (considering unhandled promise)? And if yes, will the wait3secs
be guaranteed to run (asynchronously) in firebase functions until the end, even after the response is being sent?
I have searched in Firebase (here) but haven't found a specific answer to my question.
Upvotes: 0
Views: 19
Reputation: 317467
According to the documentation:
Terminate HTTP functions with res.redirect(), res.send(), or res.end().
What this is saying is that when you call res.send()
, the function will be terminated. You should not expect any async work to complete after that - the function will be shut down.
If you need to do more work after sending the response, you will have to arrange to trigger another function to run in the background, such as a pubsub function. That function will need to return a promise that resolves only after all the async work is complete, so that it also does not get shut down prematurely.
Upvotes: 1