在Firebase云函数中返回一个Promise可以确保函数在完成其任务后才结束。这对于处理异步操作特别有用,例如从数据库读取数据或写入数据。以下是如何在Firebase云函数中返回一个Promise的示例。
functions.https.onRequest
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.myFunction = functions.https.onRequest(async (req, res) => {
try {
const result = await someAsyncOperation();
res.status(200).send(result);
} catch (error) {
res.status(500).send(error);
}
});
async function someAsyncOperation() {
return new Promise((resolve, reject) => {
// 模拟异步操作
setTimeout(() => {
resolve('Operation completed successfully');
}, 1000);
});
}
functions.firestore.document.onCreate
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.myFunction = functions.firestore
.document('myCollection/{docId}')
.onCreate(async (snap, context) => {
try {
const data = snap.data();
const result = await someAsyncOperation(data);
return result;
} catch (error) {
console.error(error);
throw new functions.https.HttpsError('internal', 'An error occurred');
}
});
async function someAsyncOperation(data) {
return new Promise((resolve, reject) => {
// 模拟异步操作
setTimeout(() => {
resolve('Operation completed successfully');
}, 1000);
});
}
functions.pubsub.schedule
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.myFunction = functions.pubsub.schedule('* * * * *').onRun(async (context) => {
try {
const result = await someAsyncOperation();
console.log(result);
return null;
} catch (error) {
console.error(error);
throw new functions.https.HttpsError('internal', 'An error occurred');
}
});
async function someAsyncOperation() {
return new Promise((resolve, reject) => {
// 模拟异步操作
setTimeout(() => {
resolve('Operation completed successfully');
}, 102
});
}
领取专属 10元无门槛券
手把手带您无忧上云