使用 Firebase 函数时获取"Function returned undefined, expected Promise or value "



我最近开始在我的Unity游戏中使用Firebase来创建一个简单的回合制游戏。第一次使用Firebase函数,更不用说对JS不熟练了。

我使用这段代码来处理一个简单的配对系统,将新添加的玩家配对到配对子数据库中,并将他们与空闲的其他玩家进行匹配,然后为游戏创建一个随机id,然后在"游戏"中创建一个新对象。sub-database .

我已经将核心上传到Firebase,并通过添加"用户"开始在实时数据库上手动测试它。但是它不工作,日志显示:

返回的函数未定义,期望的承诺或值

我在网上找过该怎么做,但我迷失了关于"承诺"的内容。在这件事上我很感激你的帮助。

下面是JS代码:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
const database = admin.database();
exports.matchmaker = functions.database.ref("matchmaking/{playerId}")
.onCreate((snap, context) => {
const gameId = generateGameId();
database.ref("matchmaking").once("value").then((players) => {
let secondPlayer = null;
players.forEach((player) => {
if (player.val() == "searching" &&
player.key !== context.params.playerId) {
secondPlayer = player;
}
});
if (secondPlayer === null) return null;
database.ref("matchmaking").transaction(function(matchmaking) {
if (matchmaking === null ||
matchmaking[context.params.playerId] !== "" ||
matchmaking[secondPlayer.key] !== "searching") {
return matchmaking;
}
matchmaking[context.params.playerId] = gameId;
matchmaking[secondPlayer.key] = gameId;
return matchmaking;
}).then((result) => {
if (result.snapshot.child(
context.params.playerId).val() !== gameId) {
return null;
}
const game = {
gameInfo: {
gameId: gameId,
playersIds: [context.params.playerId, secondPlayer.key],
},
turn: context.params.playerId,
};

database.ref("games/" + gameId).set(game).then((snapshot) => {
console.log("Game created successfully!");
return null;
}).catch((error) => {
console.log(error);
});
return null;
}).catch((error) => {
console.log(error);
});
return null;
}).catch((error) => {
console.log(error);
});
});
/**
* Generates random game id
* @return {int} Game id
*/
function generateGameId() {
const possibleChars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let gameId = "";
for (let j = 0; j < 20; j++) {
gameId +=
possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
}
return gameId;
}

更新:我能够通过在onCreate方法的末尾添加返回值来修复它。

返回上下文。

我添加了"return context">

最新更新