Firebase Pub/Sub触发Cron函数如何正确返回200响应?
Hey there, let's walk through fixing that error and clearing up your question about return values for Firebase Pub/Sub cron functions.
Why You're Seeing the Error
The "Function returned undefined..." message pops up because Firebase Cloud Functions requires your handler to return either a Promise (for async operations) or a concrete value to confirm the function finished successfully. Your current code only logs a message and doesn't return anything—hence the undefined result.
Fixing Your Code
Here's the adjusted version of your function that avoids the error:
var functions = require('firebase-functions'); exports.hourly_job = functions.pubsub.topic('hourly-tick').onPublish((event) => { console.log("This job runs every hour!"); // Return a value to signal successful completion return 200; });
If you're doing asynchronous work (like writing to Firestore, calling an external API), make sure to return a Promise (or use async/await and return a value once the async task finishes):
exports.hourly_job = functions.pubsub.topic('hourly-tick').onPublish(async (event) => { console.log("This job runs every hour!"); // Example: Wait for an async task to complete await functions.firestore.collection('logs').add({ timestamp: Date.now() }); return 200; });
Is Returning 200 Enough?
Absolutely! Returning the integer 200 is fully sufficient to mark the cron task as successful. This aligns with the retry rules you referenced:
If the cron task's request handler returns a status code outside the 200–299 (inclusive) range, App Engine marks the task as failed; by default, failed tasks won't retry, but you can enable retries by adding a
retry_parametersblock to your config file.
When you return 200 (or any value in the 200-299 range), the function is flagged as successful, so no retries will trigger unless you've explicitly enabled them in your configuration.
Quick Tips
- For synchronous work: Return any primitive value (200, "success",
true) to avoid the undefined error. - For asynchronous work: Always return the Promise so Functions knows to wait for the operation to finish before concluding the function.
- To trigger a failure (and retries if enabled), throw an error or return a rejected Promise.
内容的提问来源于stack exchange,提问作者Marcos DaSilva

