在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
});
}
小程序云开发官方直播课(应用开发实战)
云+社区技术沙龙[第14期]
云+社区技术沙龙[第22期]
T-Day
高校公开课
serverless days
云+社区技术沙龙 [第31期]
云+社区技术沙龙[第29期]
云+社区技术沙龙[第1期]
小程序云开发官方直播课(应用开发实战)
领取专属 10元无门槛券
手把手带您无忧上云