首页 > 解决方案 > 写入数据库的Firebase云函数多次写入并且永不返回

问题描述

我正在尝试创建一个云函数来写入 firebase 数据库。它应该是非常简单的。我想编写并返回 200。他们给出的示例在 then 回调中进行了重定向,但我不想重定向。不幸的是,我的函数无限期挂起,并将相同的消息写入数据库 3、4、5、6 次。

我很确定我做的退货不正确。我试图从 then 回调中返回 res.status = 200 ,但这也不起作用。

这是我目前拥有的:

exports.createEvent = functions.https.onRequest((req, res) => {
    const name = req.query.name;
    const description = req.query.description;
    const location = req.query.location; //json? lat/lng, public,
    const date = req.query.date;

    // Push the new message into the Realtime Database using the Firebase Admin SDK.
    return admin.database().ref('/Event')
        .push({name : name, description : description, location : location, date : date});
});

标签: firebasegoogle-cloud-functions

解决方案


我建议您观看有关 Cloud Functions 的官方视频系列 ( https://firebase.google.com/docs/functions/video-series/ ),尤其是有关 Promises 的第一个视频,标题为“Learn JavaScript Promises (Pt.1)使用 Cloud Functions 中的 HTTP 触发器”。

您将看到,对于 HTTTS 云函数,您必须向客户端发送响应(观看 8:50 的视频)。

因此,对您的代码进行以下修改应该可以解决问题:

exports.createEvent = functions.https.onRequest((req, res) => {
    const name = req.query.name;
    const description = req.query.description;
    const location = req.query.location; //json? lat/lng, public,
    const date = req.query.date;

    // Push the new message into the Realtime Database using the Firebase Admin SDK.
    admin.database().ref('/Event')
        .push({name : name, description : description, location : location, date : date})
        .then(ref => {
           res.send('success');
        })
        .catch(error => {
           res.status(500).send(error);
        })
});

推荐阅读