Returned gameScore Parse.Object object from Parse.

2019-08-10 22:14发布

问题:

Directly from Parse.com javascript guide:

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
  success: function(gameScore) {
    // The object was retrieved successfully.
  },
  error: function(object, error) {
    // The object was not retrieved successfully.
    // error is a Parse.Error with an error code and message.
  }
});

var score = gameScore.get("score");
var playerName = gameScore.get("playerName");
var cheatMode = gameScore.get("cheatMode");

Basically gives Uncaught ReferenceError: gameScore is not defined...

Here is my code to troubleshoot this:

// Retrieve class
var GameScore = Parse.Object.extend("GameScore"); //redefine the GameScore class based on the cloud.
var query = new Parse.Query(GameScore);
var my_object;
var some_object = query.get("SQV1DZXv5p", {
    success: function(gameScore) { //gameScore is the retrieved object.
        alert('Object retrieved, with object ID: ' + gameScore.id);
        //document.getElementById('division1').innerHTML = gameScore.id; 
        my_object = gameScore.id;

    }, 
    error: function(object, error) {
        alert('Retrieval FAILURE, error: ' + error.message + '; Object retrieved instead is: ' + object); //object will be NULL if not found.
    }
});

var score = gameScore;
document.getElementById('division1').innerHTML = my_object;

So this still throws the reference error for gameScore. Also, the document.getELementById statement does not print the gameScore.id in my division1 div. It remains empty. But when I check to see what my_object is in the javascript console, it returns the gameScore.id correctly.

What's interesting is if I run the document.getELementById line inside the success function, then it will display the gameScore.id...

回答1:

Do this:

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
  success: function(gameScore) {
    // The object was retrieved successfully.
    var score = gameScore.get("score");
    var playerName = gameScore.get("playerName");
    var cheatMode = gameScore.get("cheatMode");
  },
  error: function(object, error) {
    // The object was not retrieved successfully.
    // error is a Parse.Error with an error code and message.
  }
});

gameScore is only be available in the scope of the success block, hence the Uncaught ReferenceError. The world outside the success block does not know it exists. Do your stuff in there.

Also, .get() makes a request from the server, so it would take time to complete. Performing operations gameScore after the .get() method will result in accessing that object when it has not been fetched yet, hence another error. See @danh's comment below. For network calls like this, always perform actions on the fetched object inside the completion block.