我正在制作约会应用程序,类似于我的单例汉的 Tinder。我现在正在创建匹配系统。
我创建了 onCreate 监听器来检查用户何时按下“like”按钮,并检查其他用户是否已经对当前用户按下了“like”。这就是我尝试过的。
exports.UserPressesLike = functions.database
.ref('/users/{userId}/matches/{otherUserId}')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
const userId = context.params.userId;
const matchedUserId = context.params.otherUserId;
const a = checkUserMatch(userId, matchedUserId);
if (a === true) {
console.log('Its a match');
} else {
console.log('There is no match');
console.log(a);
}
return null;
});
checkUserMatch = async (userId, matchedUserId) => {
const snapshot = await admin
.database()
.ref('/users/' + matchedUserId + '/matches/' + userId)
.once('value')
.then(snapshot => {
// let tempuserId = snapshot.val();
// if()
return true;
});
};
我希望 checkUserMatch 如果存在该节点则返回 true,如果不存在该节点则返回 false。
最佳答案
您的 checkUserMatch
是异步的(如您用 async
标记的事实所示),这意味着它不会立即返回值,而是返回一个对象最终将包含一个值(所谓的 promise )。
要调用async
函数,您需要使用await
来调用它:
const a = await checkUserMatch(userId, matchedUserId);
这意味着您还需要将包含调用的函数标记为异步
,因此:
exports.UserPressesLike = functions.database
.ref('/users/{userId}/matches/{otherUserId}')
.onCreate(async (snapshot, context) => {
请注意,我强烈建议您在了解有关异步 API、Promises 和 async
/await
的更多信息之前不要继续。例如,通过观看 Doug 的视频系列 Learn JavaScript Promises with HTTP Triggers in Cloud Functions .
关于javascript - Firebase 检查节点是否存在返回 true 或 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60812104/