我最近开始使用Firebase和我的团结游戏来创建一个简单的基于转机的游戏。也是第一次使用Firebase函数,更不用说在JS方面没有那么熟练了。
我正在使用这个代码来处理一个简单的匹配系统,为新添加到匹配子数据库中的玩家,并将它们与空闲的其他玩家匹配,然后为游戏创建一个随机id,将其设置为它们,然后在一个“游戏”子数据库中创建一个新的对象。
我已经将内核上传到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方法的末尾添加一个返回值来修复它。
返回上下文。
发布于 2021-08-22 17:16:14
我通过在onCreate方法中添加“返回上下文”来修正它。
https://stackoverflow.com/questions/68867413
复制相似问题