node.js - 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);
}
});
解决方案
感谢@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 将信息发送回客户端。
如果遇到此问题,我建议人们阅读一些有用的链接,如下所示。
推荐阅读
- javascript - 如何从一些 JSON 数据中求和一列?
- android-studio - ClasscastException 无法转换为线性布局或 Button.widget.button
- jmeter - 下面是我需要在jmeter中使用bean shell prepocessor动态传递的数据
- sql-server - 使用 BCP 实用程序将数据导入 SQL Server(导出带有错误记录的日志文件并继续插入正常记录)
- android - 更改 android studio 中的 textview 可见性
- node.js - passport-oauth2 授权 URL 和 TokenURL 实现
- android - UI Automator Viewer 的 GUI 损坏
- android - 如何在奖励广告中添加 onAdClick 回调?- AdMob - 安卓
- javascript - 如果存在,如何从数组中删除一个值,如果不存在,如何将其推送到数组?
- javascript - 如何根据下拉菜单中的选择显示图像?