流星 - 在异步调用设置会话变量 [英] Meteor - Setting Session variables in Asynchronous Calls
问题描述
我有设置Meteor.call函数内会话变量的一个问题。看来,流星不会设置会话变量,无论我问它的功能范围之外。
I have a problem with setting session variables inside of a Meteor.call function. It appears that Meteor won't set the session variables to whatever I ask it outside of the scope of the function.
Meteor.startup(function () {
// code to run on server at startup
// prompt for name
var playerName = prompt("Please enter your name:", "");
Meteor.call('createPlayer', playerName, function(error, result) {
console.log("PLAYER_ID: " + result);
Session.set("myPlayerID", result);
console.log("SESSION_PLAYER_ID: " + Session.get("myPlayerID"));
});
console.log("SESSION_PLAYER_ID2: " + Session.get("myPlayerID"));
Session.set("gameState", SHOW_LOBBY);
});
控制台打印出来:
The console prints out:
PLAYER_ID:正确的ID
PLAYER_ID: correct ID
SESSION_PLAYER_ID:正确的ID
SESSION_PLAYER_ID: correct ID
SESSION_PLAYER_ID2:未定义
SESSION_PLAYER_ID2: undefined
正如你所看到的,会话变量不再是功能范围之外的正确。有什么建议么?
As you can see, the session variable is no longer correct outside of the scope of the function. Any suggestions?
推荐答案
要调用的createPlayer
是异步的,所以执行的顺序将是:
The call to createPlayer
is asynchronous, so the order of execution will be:
- 提示用户
- 开始调用
的createPlayer
- 请
myPlayerID
会话变量(SESSION_PLAYER_ID2) - 末梢调用
的createPlayer
:将myPlayerID
会话变量在回调
- prompt the user
- start the call to
createPlayer
- log
myPlayerID
session variable (SESSION_PLAYER_ID2) - finsh the call to
createPlayer
: set themyPlayerID
session variable in the callback
由于(4)将(3)之后,您将获得执行未定义
试图登录SESSION_PLAYER_ID2的时候。如果是这样的事情的唯一的事情(即没有一个bug其他地方在code),你应该能够做到在浏览器的控制台以下内容:
Because (4) will execute after (3), you will get undefined
when trying to log "SESSION_PLAYER_ID2". If that's the only thing going on (i.e. there isn't a bug somewhere else in your code), you should be able to do the following in your browser console:
console.log(Session.get('myPlayerID'));
和,希望,你会得到正确的结果。因此,要回答你原来的问题:我看不出这里有什么问题 - 会话变量依然会范围外提供。这似乎只是一个异步函数的行为的误解。
And, hopefully, you will get the correct result. So to answer your original question: I don't see anything wrong here - the Session variable will still be available outside of the scope. This appears to be just a misunderstanding of the behavior of asynchronous functions.
这篇关于流星 - 在异步调用设置会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!