首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

从Firebase云函数返回promise

在Firebase云函数中返回一个Promise可以确保函数在完成其任务后才结束。这对于处理异步操作特别有用,例如从数据库读取数据或写入数据。以下是如何在Firebase云函数中返回一个Promise的示例。

使用 functions.https.onRequest

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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
  });
}
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券