JS 对象奇怪的行为

JS Object odd behavior

我目前正在尝试使用 Phaser 和 Eureca io 构建多人游戏。我正处于尝试确定玩家的身份验证以及他们控制的内容的阶段,我通过在服务器上使用 returns 正确的玩家 ID 的方法来做到这一点。

服务器上的方法是-

 eurecaServer.exports.getPlayer2Id = function(name , id)
 {

   if(name == "Fly" && id == player2id)
   {
     console.log("correct fly player");
     return player2id;
   }
   else
   {
     console.log("Wrong fly player");
     return id;
   }
}

目前在客户端,我只是在测试,但是当我调用函数时,它 returns 是一个对象。当简单地查看控制台中的对象时,它会显示这个。 Object {status: 0, result: null, error: null, sig: "eY0IjunQt7"} 所以它告诉我我的结果是空的,这很奇怪,但是当扩展它时我得到了。

Object {status: 0, result: null, error: null, sig: "eY0IjunQt7"} callback: function() error: null errorCallback: function() onReady: (fn, errorFn) result: "jVcZvzetc8AAK45NAAAH" sig: "eY0IjunQt7"

正如您在展开结果时看到的那样,结果不为空,这正是我正在寻找的,我已经尝试过,JSON.stringify 但它给了我第一个结果,它告诉我结果为空.

关于如何获得实际结果或为什么会发生这种情况的任何想法。

谢谢。

编辑:

服务器的客户端组件在主游戏文件中定义

var eurecaClientSetup = function() {

var eurecaClient = new Eureca.Client();

eurecaClient.ready(function (proxy) {
    eurecaServer = proxy;

});

然后在对象class这里调用

this.name = "Fly"
this.id = index;  //Passed in on object creation
this.currPlayer = eurecaServer.getPlayer2Id(this.name, this.id);
console.log(JSON.stringify(this.currPlayer));
console.log(this.currPlayer);

任何服务器操作都将是异步的,与框架无关*。一旦结果可用,不同的框架有不同的获取结果的方法。在 Eureca.io 中,它似乎在服务器函数名称后使用 .onReady() 调用。

换句话说,您需要做的就是将您的客户端代码更改为以下内容:

this.name = "Fly"
this.id = index;  //Passed in on object creation
var _this = this; // needed because "this" inside function below won't be the same
eurecaServer.getPlayer2Id(this.name, this.id).onReady(function (id) {
    _this.currPlayer = id;
    console.log(_this.currPlayer); // shows the right thing
    // do other stuff here now you have the right player id
});

* 从技术上讲,您可以执行 synchronous/blocking AJAX 请求,但在 99% 的情况下这是不好的做法。

我是eureca.io的作者,GregL给出的答案是正确的。 我只想补充一点,onReady() 调用将被弃用,eureca.io 支持类似调用的承诺(使用 then() 函数)。

所以你可以改用这个语法,它更标准。

this.name = "Fly"
this.id = index;  //Passed in on object creation
var _this = this; // needed because "this" inside function below won't be the same
eurecaServer.getPlayer2Id(this.name, this.id).then(function (id) {
    _this.currPlayer = id;
    console.log(_this.currPlayer); // shows the right thing
    // do other stuff here now you have the right player id
});