success/error 在 Parse.Promise

success/error on Parse.Promise

我已经编写了一系列 Parse Promises,现在当我向这个云代码函数发出请求时收到错误 141。我尝试将 success: / error: 放置在我认为它们属于基于 Parse DOCS 的函数中。

Request

 {
   "projectDescription": "Testing saveProject",
   "projectTitle": "This is only a test, in the event of a real post this will have an actual description",
   "isEmailEnabled": true,
   "shareEmails": [
     "max@gmail.com",
     "nat@gmail.com",
     "noob@gmail.com"
   ],
   "userId": "sLmOf4fZFL"
 }

  Parse.Cloud.define("saveProject", function(request, response) {

    var emails = request.params.shareEmails;
    var user = request.params.userId;
    var projectDescription = request.params.projectDescription;
    var projectTitle = request.params.projectTitle;
    var emailStatus = request.params.isEmailEnabled;

    var ProjectClass = Parse.Object.extend("Project");

    var EmailsClass = Parse.Object.extend("Email");

    var EmailsClassAssignment = Parse.Object.extend("EmailAssignment");

    var project = new ProjectClass();

    var projectO;


        project.set("title", projectTitle);
        project.set("createdBy", {
                        "__type": "Pointer",
                        "className": "_User",
                        "objectId": user
        });
        project.set("description", projectDescription);
        project.set("status", true);
        project.set("emailShareEnabled", emailStatus);
        project.save().then(function(results) {

            projectO = results;

            console.log(projectO);

        return Parse.Promise.when(emails.map(function(emailAddress) {

                var email = new EmailsClass();
                email.set("address", emailAddress);
                return email.save();

            }));
        }).then(function() {
        return Parse.Promise.when(emails.map(function(emailQuery) {

            var queryEmail = new Parse.Query("Email");
            queryEmail.equalTo("address", emailQuery);
            return queryEmail.find().then(function(results) {

                var emailJSON = results[0].toJSON();
                var emailObjectId = emailJSON.objectId;

                var projectJSON = projectO.toJSON();

                var projectId = projectJSON.objectId;

                var assignment = new EmailsClassAssignment();

                assignment.set("createdBy", {
                                    "__type": "Pointer",
                                    "className": "_User",
                                    "objectId": user
                });
                assignment.set("email", {
                                    "__type": "Pointer",
                                    "className": "Email",
                                    "objectId": emailObjectId
                });
                assignment.set("project", {
                                    "__type": "Pointer",
                                    "className": "Project",
                                    "objectId": projectId
                });
                assignment.save(null, {
                    success: function() {
                        console.log("Successfully saved project");
                    },
                    error: function(error) {
                        console.log("There was an error saving" + error.message);
                    }
                });
            });
        }));
    }).then( function() {
        response.success();
    });
});

基本思路看起来不错,但代码有点乱,回调参数和承诺。我冒昧地重构为更简单的、有希望的-returning 逻辑块,这样我们就可以看到发生了什么。

您在 post 中突出显示了 .map 函数。不知道是什么问题,所以我建议的代码使用underscorejs,可以很容易地包含在云中,如下所示:

var _ = require('underscore');

首先,return 承诺将 "project" 给定的大部分参数保存到您的云函数:

function createProject(params) {
    var ProjectClass = Parse.Object.extend("Project");
    var project = new ProjectClass();

    var emails = request.params.shareEmails;
    var user = request.params.userId;
    var projectDescription = request.params.projectDescription;
    var projectTitle = request.params.projectTitle;
    var emailStatus = request.params.isEmailEnabled;

    project.set("title", projectTitle);
    project.set("createdBy", {
                    "__type": "Pointer",
                    "className": "_User",
                    "objectId": user
    });
    project.set("description", projectDescription);
    project.set("status", true);
    project.set("emailShareEnabled", emailStatus);
    return project.save();
}

接下来,根据电子邮件地址字符串数组创建 "Email"(对象)。 (你最好仔细区分命名中的对象和字符串,但我试图在代码中遵循原始命名法)

function createEmails(emails) {
    var EmailsClass = Parse.Object.extend("Email");
    var toSave = _.map(emails, function(emailAddress) {
        var email = new EmailsClass();
        email.set("address", emailAddress);
        return email;
    });
    // like the when() function, but (possibly) fewer requests
    return Parse.Object.saveAll(toSave);
}

这是原始代码变得更糟的地方。在其中,代码刚刚完成创建电子邮件对象,然后出于某种原因,它尝试查询这些对象。但是我们已经有了它们,兑现了拯救的承诺。

下面的方法将已经构建的电子邮件对象(学究式命名,以强调它们是对象)和其他成分放入 "EmailClassAssignment"。当我们手头有一个 PFObject 时,请注意我们如何直接用对象分配指针:

function createEmailClassAssignments(emailObjects, project, userId) {
    var EmailsClassAssignment = Parse.Object.extend("EmailAssignment");
    var toSave = _.map(emailObjects, function(emailObject) {
        var assignment = new EmailsClassAssignment();
        // the real objects can be used as parameters to set for pointer columns
        assignment.set("email", emailObject);
        assignment.set("project", project);
        // we only have the userId, not a user object, so we can either query
        // for the user or take the shortcut that you've been taking
        project.set("createdBy", {
                        "__type": "Pointer",
                        "className": "_User",
                        "objectId": user
        });
        return assignment;
    });
    return Parse.Object.saveAll(toSave);
}

完成所有这些后,云函数变得更加清晰:

Parse.Cloud.define("saveProject", function(request, response) {
    var project;
    createProject(params).then(function(result) {
        project = result;
        return createEmails(request.params.shareEmails);
    }).then(function(emailObjects) {
        return createEmailClassAssignments(emailObjects, project, request.params.userId);
    }).then(function() {
        console.log("Successfully saved project");
        // I took the liberty of returning the new project to the caller
        response.success(project);
    }, function(error) {
        console.log("There was an error saving" + error.message);
        resoonse.error(error);
    });
});

注意:显然,我无法测试上述任何一项。我强烈建议您自己测试这些功能,最好是在期望组合起作用之前单独测试。希望重构展示了一种更简洁的方式来使用 promises 和合理分解的部分以单独测试和使用。

从代码的外观来看,您只需在 assignment.save() 前面添加一个 return,因为您不需要等待它完成。

最后你应该在最后添加一个错误捕捉器:

.then(null, function(error) {
  console.log(error);
  response.error(error);
});