首页 > 解决方案 > Firebase 函数仅返回 null

问题描述

这样做的目的是让我从我的数据库中获取所有日期,从最新到最旧组织它们,按该顺序从我的数据库中获取所需的信息并发送该客户端。该代码在服务器端工作,所有信息都是正确的。我只需要将它发送给我的客户。我的客户端接收字符串和我发送的任何内容,我认为问题在于我的返回语句在哪里。提前感谢任何试图帮助我的人。

这是我的服务器端代码:

exports.loadNewestPlaylist = functions.https.onCall((request, response) => {
    try {
        var dates = [];
        var Info = [];
        var query = admin.database().ref().orderByKey();

        query.once("value")
            .then(function (snapshot) {
                snapshot.forEach(function (snapshot) {
                    if (dates.indexOf(snapshot.child("Date").val()) > -1) {}
                    else {
                        dates.push(snapshot.child("Date").val());
                        dates.sort(date_sort_asc);
                    }
                });

                dates.forEach(function (date) {
                    query.once("value")
                        .then(function (snapshot) {
                            snapshot.forEach(function (snapshot) {
                                if (date === snapshot.child("Date").val()) {
                                    Info.push(snapshot.child("Url").val(), snapshot.key);
                                }
                            });

                        });

                });

                return Info;

            });

        var date_sort_asc = function (date1, date2) {
            if (date1 > date2) return 1;
            if (date1 < date2) return -1;
            return 0;
        };
    }

    catch (error) {
        console.error(error);
    }
});

标签: node.jsfirebasegoogle-cloud-functions

解决方案


感谢@DougStevenson,我终于得到了答案!

try {
    var dates = [];
    var Info = [];
    var query = admin.database().ref().orderByKey();

    return new Promise((resolve, reject) => {

        query.once("value").then(function (snapshot) {

            snapshot.forEach(function (snapshot) {
                if (dates.indexOf(snapshot.child("Date").val()) > -1) { }
                else {
                    dates.push(snapshot.child("Date").val());
                    dates.sort(date_sort_asc);
                }
            });

            dates.forEach(function (date) {
                snapshot.forEach(function (snapshot) {
                    if (date === snapshot.child("Date").val()) {
                        Info.push(snapshot.child("Url").val(), snapshot.key);
                    }
                });
            });
            resolve(Info);
        });
    });

    loadNewestPlaylist().then(result => {
        return result;
    });

    var date_sort_asc = function (date1, date2) {
        if (date1 > date2) return 1;
        if (date1 < date2) return -1;
        return 0;
    };
}

catch (error) {
    console.error(error);
}

我需要使用 Promise 将信息发送回客户端。

如果遇到此问题,我建议人们阅读一些有用的链接,如下所示。

Firebase 同步、异步和承诺

承诺 | MDN

承诺的例子


推荐阅读