gpt4 book ai didi

javascript - 在 Meteor.startup 的客户端案例中等待多个订阅

转载 作者:行者123 更新时间:2023-12-02 17:46:45 25 4
gpt4 key购买 nike

我认为我的 Meteor 客户端启动代码遇到了竞争条件。

简要背景

我正在使用 Meteor 作为 HTML5 游戏大厅界面。当用户通过刷新页面或稍后返回返回菜单时,我希望客户端找到该用户正在进行的任何游戏。但是,我在启动过程中无法访问任何集合。

下面显示了我的 client.js 文件顶部的摘录。

Meteor.subscribe("players"); //Meteor.Collection("players" references Meteor.users via user_id
Meteor.subscribe("games"); // each player has a game_id, linked to Meteor.Collection("games"
if (Meteor.isClient) {
Meteor.startup(function () {
//find the player from the user_id, find game from player.game_id
var current_user_id = Meteor.userId();
var playerFromUser = Players.findOne({"user_id":current_user_id});
if(typeof playerFromUser !== 'undefined'){
var getGame = Games.findOne(playerFromUser.game_id);
if(typeof getGame !== 'undefined'){
alert('game found!'); //is not reached
}else{
alert('game not found'); //is not reached
}
}else{
alert('player not found'); //*********** IS reached. Why? ***********
}
});
}

但是,我可以从 javascript 控制台运行 Players.findOne({"user_id":Meteor.userId()); 并且它可以很好地返回有效的 Player。 我的收藏中出现这种竞争状况是怎么回事?

编辑1:

深入研究该库,我发现我错误地认为来自服务器的数据将立即可用。订阅实际上需要一段时间来处理,这就是为什么它们在客户端启动时不可用的原因。我正在更新我的问题以表达这些新信息。

更新的问题

由于我依赖多个订阅来为用户(玩家和游戏)查找游戏,是否有 Meteor 方式来等待两者?仅仅为了获得正在进行的游戏而单独订阅似乎是错误的。根本不需要任何服务器调用。

我觉得应该能够从检索到的玩家和游戏中找到我需要的游戏,而不会再通过任何调用来打扰服务器。

一旦找到自己的解决方案,我就会在这里发布。

最佳答案

好吧,这就是我所拥有的似乎有效的方法:

基本上,我在 session 中添加了在两个订阅的就绪回调上设置的标志。然后,Deps.autorun 函数会监听要设置的 Session 值并执行其余操作。

if (Meteor.isClient) {
Meteor.subscribe("players", function(){
console.log("players_loaded ");
Session.set('players_loaded', true);
}); //linked to Meteor.users with user_id


Meteor.subscribe("games", function(){
console.log("games_loaded ");
Session.set('games_loaded', true);
}); // each player has a game_id


Deps.autorun(function(){
var gamesLoaded = Session.get('games_loaded');
var playersLoaded = Session.get('players_loaded');
if(gamesLoaded && playersLoaded &&
(typeof Players !== 'undefined') && (typeof Games !== 'undefined') ) {
console.log("both loaded! ");
//find the player from the user_id, find game from player.game_id
var playerFromUser = Players.findOne({"user_id":Meteor.userId()});
if(typeof playerFromUser !== 'undefined'){
var getGame = Games.findOne(playerFromUser.game_id);
if(typeof getGame !== 'undefined'){
console.log("game found : " + getGame);
//Do stuff with the game now that we have it
}else{
console.log("no game :(");
}
}else{
console.log("no player :(");
}
}
});

Meteor.startup(function () {
Session.set("title", "whatever else");
Session.set("games_loaded", false);
Session.set("players_loaded", false);
console.log("DOM loaded");
});

}

希望我能帮助别人。

关于javascript - 在 Meteor.startup 的客户端案例中等待多个订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21692201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com