Parse.Com - HTTP method in cloud code, how do I wait for the response

假如想象 提交于 2019-12-08 03:09:49

问题


In my parse cloud code, the HttpRequest in beforeSave is getting executed successfully but the code blows through before I have had time to parse the response and determine whether I want to return a response.success() or a response.error().

I know I am missing something here, any input, ideas from the community here would be appreciated. Thanks

Parse.Cloud.beforeSave(Parse.User, function (request, response) {    
    var user = request.object;
    var key = user.get("recaptcha");  

        Parse.Cloud.httpRequest({
        url: 'https://www.google.com/recaptcha/api/siteverify?secret=<ITS A SECRET>&response=' + key,
        success: function (httpResponse) {
            var status = JSON.parse(httpResponse.text).success;
            console.log(status);
            if (status === false) {
                response.error();
            } else {
                response.success();
            }
        }
    });
});

回答1:


I got it working...Parse.Cloud.httpRequest() is asynchronous, here is the solution that worked for me, hope it helps someone else.

Parse.Cloud.beforeSave(Parse.User, function (request, response) {    
    var user = request.object;
    var key = user.get("recaptcha");  
    if (!request.object.existed()) {
        return Parse.Cloud.httpRequest({
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },                
            url: 'https://www.google.com/recaptcha/api/siteverify?secret=<ITS A SECRET>&response=' + key,
            body: request,
            success: function(httpResponse) {
                var status = JSON.parse(httpResponse.text).success;
                if (status === false) {
                    response.error();
                } else {
                    response.success();
                }
            },
            error: function(httpResponse) {
                response.error(httpResponse);
            }  
        });
        }
       });


来源:https://stackoverflow.com/questions/33554682/parse-com-http-method-in-cloud-code-how-do-i-wait-for-the-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!