2014-10-09 114 views
6

我想从objectId获取用户对象。我知道objectId是有效的。但我可以得到这个简单的查询工作。它有什么问题?查询后用户仍未定义。解析云代码检索objectId用户

var getUserObject = function(userId){ 
    Parse.Cloud.useMasterKey(); 
    var user; 
    var userQuery = new Parse.Query(Parse.User); 
    userQuery.equalTo("objectId", userId); 

    userQuery.first({ 
     success: function(userRetrieved){ 
      console.log('UserRetrieved is :' + userRetrieved.get("firstName")); 
      user = userRetrieved;    
     } 
    }); 
    console.log('\nUser is: '+ user+'\n'); 
    return user; 
}; 

回答

20

使用承诺的快速云代码示例。我在那里有一些文档,我希望你可以关注。如果您需要更多帮助,请告诉我。

Parse.Cloud.define("getUserId", function(request, response) 
{ 
    //Example where an objectId is passed to a cloud function. 
    var id = request.params.objectId; 

    //When getUser(id) is called a promise is returned. Notice the .then this means that once the promise is fulfilled it will continue. See getUser() function below. 
    getUser(id).then 
    ( 
     //When the promise is fulfilled function(user) fires, and now we have our USER! 
     function(user) 
     { 
      response.success(user); 
     } 
     , 
     function(error) 
     { 
      response.error(error); 
     } 
    ); 

}); 

function getUser(userId) 
{ 
    Parse.Cloud.useMasterKey(); 
    var userQuery = new Parse.Query(Parse.User); 
    userQuery.equalTo("objectId", userId); 

    //Here you aren't directly returning a user, but you are returning a function that will sometime in the future return a user. This is considered a promise. 
    return userQuery.first 
    ({ 
     success: function(userRetrieved) 
     { 
      //When the success method fires and you return userRetrieved you fulfill the above promise, and the userRetrieved continues up the chain. 
      return userRetrieved; 
     }, 
     error: function(error) 
     { 
      return error; 
     } 
    }); 
}; 
+0

不知道query.first()方法。感谢你! – 2015-09-01 22:37:02

+0

Parse.Cloud.useMasterKey();已在Parse Server版本2.3.0(2016年12月7日)中弃用。从那个版本开始,它是一个无操作(它什么都不做)。您现在应该将{useMasterKey:true}可选参数插入到需要在代码中重写ACL或CLP的每个方法中。 – alvaro 2017-06-01 00:27:45

0

问题在于Parse查询是异步的。这意味着它将在查询有时间执行之前返回user(null)。无论您想如何处理用户,都需要放在成功之中。希望我的解释能帮助你理解为什么它是未定义的。

调查Promises。从第一个查询中得到结果后,这是更好的方法。

+0

我试过从成功内退回,它没有工作。我将考虑到查询是异步的这一事实;我没有意识到这一点。 – Ben 2014-10-09 20:40:00

+0

您可以将其余的功能添加到成功中吗? – Dehli 2014-10-09 20:40:55

+0

我会尝试使用承诺在成功案例中继续。 – Ben 2014-10-09 20:57:42