【问题标题】:Parse Cloud Code retrieving a user with objectId解析云代码检索具有 objectId 的用户
【发布时间】:2014-12-04 21:14:55
【问题描述】:

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

【问题讨论】:

    标签: parse-platform parse-cloud-code


    【解决方案1】:

    使用 Promise 的快速云代码示例。我有一些文档,希望你能关注。如果您需要更多帮助,请告诉我。

    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() 方法一无所知。谢谢!
    • Parse.Cloud.useMasterKey();已在 Parse Server 版本 2.3.0(2016 年 12 月 7 日)中弃用。从那个版本开始,它是一个无操作(它什么都不做)。您现在应该将 {useMasterKey:true} 可选参数插入到需要在代码中覆盖 ACL 或 CLP 的每个方法中。
    【解决方案2】:

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

    查看Promises。在您从第一个查询中获得结果后,这是一种更好的调用方式。

    【讨论】:

    • 我尝试从成功中返回,但没有成功。我会考虑查询是异步的这一事实;我没有意识到这一点。
    • 您能否将其余功能添加到成功中?
    • 我会尝试在成功的情况下使用 Promise 继续进行。
    猜你喜欢
    • 2015-05-24
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多