解析云代码检索具有objectId的用户

8

我正在尝试从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;
};
2个回答

23

使用 Promises 的快速云代码示例。我在其中添加了一些文档,希望您能够理解。如果您需要更多帮助,请告诉我。

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;
        }
    });
};

不知道query.first()方法,谢谢你! - Caleb Faruki
1
Parse.Cloud.useMasterKey(); 已在 Parse Server 版本 2.3.0 (2016年12月7日) 中被弃用。从该版本开始,它是一个无操作(不执行任何操作)。现在,您应该在需要覆盖代码中的 ACL 或 CLP 的每个方法中插入 {useMasterKey:true} 可选参数。 - alvaro

0

这个问题在于Parse查询是异步的。这意味着在查询有时间执行之前,它将返回用户(null)。您想要对用户进行的任何操作都需要放在成功的内部。希望我的解释能帮助您理解为什么它是未定义的。

研究一下Promises。这是一种更好的方式,在第一个查询获得结果后调用某些内容。


我已经尝试从成功的函数中返回,但没有起作用。我会考虑到查询是异步的这一事实;我之前没有意识到。 - Ben
你能把剩下的功能加入到成功中吗? - Dehli
我会尝试使用 Promise 在成功的情况下继续执行。 - Ben

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接