0

我正在尝试设置一个允许与随机玩家一起玩的游戏。下面的代码应该为两个配对玩家创建一个 GameMessage 对象。为了将这两个对象关联为同一个游戏的一部分,我决定将为“firstplayer”制作的游戏的 objectId 保存在“otherside”字段中的“secondplayer”中,反之亦然。出于某种原因(也许在代码尝试检索 objectIds 之前没有完成 firstplayer 和 secondplayer 的第一次保存,这意味着没有要获取的 objectIds?)。

简短版本:为什么“其他”值没有保存?

Parse.Cloud.define("findpartner", function(request, response) {

var User = Parse.Object.extend("_User");
var user = new User();

var currentuser = Parse.User.current();
currentuser.set("searching", 0);


var query = new Parse.Query(User);
query.equalTo("searching", 1);
query.limit(50); //limit to at most 50 users
query.find({
    success: function(objects) {
        var amount = objects.length;
        var indexNum = Math.floor((Math.random() * amount));
         var newpartner = objects[indexNum];
                   if (amount > 0 && newpartner.id !=currentuser.id) {



            newpartner.set("searching", 0);

            var Firstplayer = Parse.Object.extend("GameMessages");
            var firstplayer = new Firstplayer();

            var Secondplayer = Parse.Object.extend("GameMessages");
            var secondplayer = new Secondplayer();

            firstplayer.set("sender", currentuser.id);
            firstplayer.set("receiver", newpartner.id);
            firstplayer.set("sent",0);
            firstplayer.set("received",0);
            firstplayer.set("receiverName", newpartner.getUsername());

            secondplayer.set("sender", newpartner.id);
            secondplayer.set("receiver", currentuser.id);
            secondplayer.set("sent",0);
            secondplayer.set("received",0);
            secondplayer.set("receiverName", currentuser.getUsername());

            firstplayer.save().then(function(secondplayer){               <<<
                return secondplayer.save();                               <<<

                }).then(function(firstplayer_update) {                    <<<
                return firstplayer.save({ otherside: secondplayer.id});   <<<

            }).then(function(secondplayer_update){                        <<<
                return secondplayer.save({ otherside: firstplayer.id});   <<<

            });


            newpartner.save(null, {useMasterKey: true});

        }
                    else {
                        currentuser.set("searching", 1);
                    }
        currentuser.save();
        response.success(amount);
      },
    error: function(error) {
        alert("Error: " + error.code = " " + error.message);
      }
   });    

});

我添加了箭头来显示“另一边”在哪里。它们不在实际代码中。我不怀疑代码有错误,但我不知道 javascript。我完全通过研究 parse.com 文档来编写它。

4

2 回答 2

0
        firstplayer.save();
        secondplayer.save();

        secondplayer.set("otherside",firstplayer.id);     <<<
        firstplayer.set("otherside",secondplayer.id);     <<<

        firstplayer.save();
        secondplayer.save(); 

这是您说不起作用的代码部分。在解析文档中,您可以看到这.save()是一个非阻塞操作。表示该行firstplayer.save()立即转到下一行(它不会阻塞线程进行保存)。所以当你设置 idsecondplayer.set("otherside",firstplayer.id) firstplayer.id仍然是未定义的。

所以如果你想要一个同步逻辑,比如先保存 first_object 然后保存 second_object ,你必须使用回调。

first_object.save({
    success: function(saved_first_object) {
       second_object.save({
          success: function(saved_second_object) {
             //process complete
          },
          failure: function(error){

          }
       })
    },
    failure: function(error) {
       console.log(error);
    } 

})

你也可以使用 Promise 来处理它。 http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/

更新:基于 OP 尝试承诺的问题编辑

试试这个

            firstplayer.save()
            .then(function(saved_firstPlayer){
            firstplayer = saved_firstPlayer;               
            return secondplayer.save();                               

            }).then(function(saved_secondplayer) {
                 secondplayer = saved_secondplayer;                    
                 return firstplayer.save({ otherside: secondplayer.id});   

           }).then(function(updated_firstplayer){ 
               firstplayer = updated_firstplayer;                       
               return secondplayer.save({ otherside: firstplayer.id}); 

           }).then(function(updated_secondlayer){ 
              secondplayer= update_secondplayer;
           });
于 2014-07-11T20:55:40.407 回答
0

我不相信创建这 2 个独立的消息并将它们链接在一起是否有意义,但我不会让这妨碍它的工作。这未经测试,但我已经重构了您的代码,并认为您应该尝试从中收集一些东西。

// Set this up once, outside of your function, and use it everywhere
var GameMessage = Parse.Object.extend("GameMessages");

Parse.Cloud.define("findpartner", function(request, response) {

    // Code defensively, make sure this function requires a user be logged in.
    if (!request.user) {
        console.log("non-user called findpartner");
        return response.error("Unauthorized.");
    }

    // Get the user who called the function
    var user = request.user;
    // The end response is a number, apparently
    var result = 0;
    // The target player
    var targetPlayer;
    // The two messages that will be used if a match is found
    var firstmsg = new GameMessage();
    var secondmsg = new GameMessage();

    // Create a Users query
    var query = new Parse.Query(Parse.User);
    query.equalTo("searching", 1);
    query.notEqualTo("objectId", user.id);
    query.limit(50);
    // Remove public access to Find operations for Users in the Data Browser
    // Use the master key to query, and use promise syntax.
    query.find({ useMasterKey: true }).then(function(objects) {
        result = objects.length;
        // If no users were found searching, mark the user as searching and save
        if (result == 0) {
            user.set('searching', 1);
            // Return the save promise
            return user.save(null, { useMasterKey: true });
        }
        // Pick a random user out of the response
        var indexNum = Math.floor((Math.random() * objects.length));
        var targetPlayer = objects[indexNum];
        // Set that user to no longer be searching and save
        targetPlayer.set("searching", 0);
        return targetPlayer.save(null, { useMasterKey: true }).then(function() {

            firstmsg.set("sender", user.id);
            firstmsg.set("receiver", targetPlayer.id);
            firstmsg.set("sent", 0);
            firstmsg.set("received", 0);
            firstmsg.set("receiverName", targetPlayer.getUsername());

            secondmsg.set("sender", targetPlayer.id);
            secondmsg.set("receiver", user.id);
            secondmsg.set("sent", 0);
            secondmsg.set("received", 0);
            secondmsg.set("receiverName", user.getUsername());

            // Return the promise result of saving both messages
            return Parse.Object.saveAll([firstmsg, secondmsg], { useMasterKey: true });

        }).then(function(messages) {

            // Set the pointers to reference each other
            firstmsg.set("otherside", secondmsg.id);
            secondmsg.set("otherside", firstmsg.id);
            // Return the promise result of saving both messages, again
            return Parse.Object.saveAll([firstmsg, secondmsg], { useMasterKey: true });
        });
    }).then(function() {
        // All the stuff above has finished one way or the other, now we just need to 
        // send back the result. 0 if no match was made.
        response.success(result);
    }, function(error) {
        response.error(error);
    });

});
于 2014-07-11T21:32:51.717 回答