Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Bạn cần quản lý vòng đời của một hàm để đảm bảo hàm đó phân giải đúng cách. Bằng cách chấm dứt các hàm đúng cách, bạn có thể tránh bị tính phí quá mức đối với những hàm chạy quá lâu hoặc lặp lại vô hạn. Ngoài ra, bạn có thể đảm bảo rằng phiên bản Cloud Functions chạy hàm của bạn không tắt trước khi hàm đạt đến trạng thái hoặc điều kiện kết thúc thành công.
Hãy sử dụng các phương pháp được đề xuất sau đây để quản lý vòng đời của các hàm:
Giải quyết các hàm thực hiện quy trình xử lý không đồng bộ (còn gọi là "hàm nền") bằng cách trả về một lời hứa JavaScript.
Chấm dứt các hàm HTTP bằng res.redirect(), res.send() hoặc res.end().
Kết thúc hàm đồng bộ bằng câu lệnh return;.
Đơn giản hoá mã không đồng bộ bằng các promise trong JavaScript
Promise là một giải pháp thay thế hiện đại cho lệnh gọi lại đối với mã không đồng bộ. Một promise biểu thị một thao tác và giá trị trong tương lai mà thao tác đó có thể trả về. Việc này cũng cho phép bạn truyền lỗi tương tự như try/catch trong mã đồng bộ. Bạn có thể đọc về các promise trong Firebase SDK trên Blog của Firebase và các promise nói chung trên MDN.
Cách hoạt động của promise với các hàm
Khi bạn trả về một promise JavaScript cho một hàm, hàm đó sẽ tiếp tục chạy cho đến khi promise được giải quyết hoặc bị từ chối. Để cho biết một hàm đã hoàn tất công việc thành công, lời hứa phải được giải quyết. Để cho biết lỗi, promise phải bị từ chối. Điều này có nghĩa là bạn chỉ cần xử lý những lỗi mà bạn muốn.
Đoạn mã sau đây lấy một Firebase Realtime Databaseref và đặt giá trị của nó thành "world!". Bằng cách trả về kết quả của set, hàm của bạn được đảm bảo sẽ tiếp tục chạy cho đến khi công việc không đồng bộ ghi chuỗi vào cơ sở dữ liệu hoàn tất:
Hầu hết các Cloud Functionsmã mẫu của chúng tôi đều có ví dụ về cách chấm dứt hàm đúng cách. Sau đây là một vài ví dụ minh hoạ các trường hợp điển hình:
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2025-09-03 UTC."],[],[],null,["\u003cbr /\u003e\n\nIt's important to manage the lifecycle of a function to ensure that it resolves\nproperly. By terminating functions correctly, you can avoid excessive charges\nfrom functions that run for too long or loop infinitely. Also, you can make sure\nthat the Cloud Functions instance running your function does not shut down\nbefore your function successfully reaches its terminating condition or state.\n\nUse these recommended approaches to manage the lifecycle of your functions:\n\n- Resolve functions that perform **asynchronous** processing (also known as \"background functions\") by returning a [JavaScript\n promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n- Terminate **HTTP functions** with `res.redirect()`, `res.send()`, or `res.end()`.\n- Terminate a **synchronous** function with a `return;` statement.\n\n| **Caution:** In all cases, be careful to avoid any situation in which the function's result actually retriggers the function --- for example, a function triggered by writes to a specific Realtime Database path that concludes by writing to that same path.\n\nSimplify asynchronous code with JavaScript promises\n\nPromises are a modern alternative to callbacks for asynchronous code. A promise\nrepresents an operation and the future value it may return. It also lets you\npropagate errors similar to try/catch in synchronous code. You can read about\npromises in the Firebase SDK on [The Firebase\nBlog](https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html),\nand promises in general on\n[MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n\nHow promises work with functions\n\nWhen you return a JavaScript promise to a function, that function\nkeeps running until the promise is resolved or rejected. To indicate that a\nfunction has completed its work successfully, the promise should be resolved. To\nindicate an error, the promise should be rejected. This means you only need to\nhandle errors that you want to.\n\nThe following code takes a Firebase Realtime Database `ref` and sets its value to\n`\"world!\"`. By returning the result of `set`, your function is guaranteed to\nkeep running until the asynchronous work of writing the string to the database\nis fully completed: \n\n // Always change the value of \"/hello\" to \"world!\"\n exports.hello = functions.database.ref('/hello').onWrite(event =\u003e {\n // set() returns a promise. We keep the function alive by returning it.\n return event.data.ref.set('world!').then(() =\u003e {\n console.log('Write succeeded!');\n });\n });\n\nExamples in context\n\nMost of our Cloud Functions [code\nsamples](https://github.com/firebase/functions-samples)\ninclude examples of proper function termination. Here are a few that demonstrate\ntypical cases:\n\n- [Realtime Database\n trigger](https://github.com/firebase/functions-samples/tree/main/Node-1st-gen/quickstarts/uppercase-rtdb/functions/index.js): an HTTP function followed by a redirect\n- [Cloud Storage\n trigger](https://github.com/firebase/functions-samples/tree/main/Node-1st-gen/quickstarts/thumbnails/functions/index.js): A storage download followed by `then`\n- [Webhook on Realtime Database\n write](https://github.com/firebase/functions-samples//tree/main/Node-1st-gen/minimal-webhook/functions/index.js): An error thrown inside a `then` clause\n- [Periodically delete unused\n accounts](https://github.com/firebase/functions-samples//tree/main/Node-1st-gen/delete-unused-accounts-cron/functions/index.js): A rejected promise"]]