0

我正在写一份我想在 Parse 的后台每小时运行一次的工作。我的数据库有两个表。第一个包含Questions 的列表,而第二个列出所有用户\问题协议对 ( QuestionAgreements)。最初我的计划只是让客户端QuestionAgreement自己计算 s,但我发现这会导致很多请求确实可以取消,所以我希望这个后台作业运行计数,然后更新字段直接Question用它。

这是我的尝试:

Parse.Cloud.job("updateQuestionAgreementCounts", function(request, status) {
    Parse.Cloud.useMasterKey();
    var query = new Parse.Query("Question");
    query.each(function(question) {
        var agreementQuery = new Parse.Query("QuestionAgreement");
        agreementQuery.equalTo("question", question);
        agreementQuery.count({
            success: function(count) {
                question.set("agreementCount", count);
                question.save(null, null);
            }
        });
    }).then(function() {
        status.success("Finished updating Question Agreement Counts.");
    }, function(error) {
        status.error("Failed to update Question Agreement Counts.")
    });
});

问题是,这似乎只在几个Questions 上运行,然后停止,在 Parse Dashboard 的 Job Status 部分显示为“成功”。我怀疑问题是它过早地返回。以下是我的问题:

1 - 我怎样才能防止它过早返回?(假设这是,事实上,我的问题。)

2 - 调试云代码的最佳方法是什么?由于这不是客户端,我没有办法设置断点或任何东西,对吗?

4

2 回答 2

1

status.success在异步成功调用count完成之前调用。为了防止这种情况,您可以在此处使用 Promise。检查Parse.Query.each的文档。

遍历查询的每个结果,为每个结果调用回调。如果回调返回一个承诺,则迭代将不会继续,直到该承诺已被履行。

因此,您可以链接count承诺:

agreementQuery.count().then(function () {
    question.set("agreementCount", count);
    question.save(null, null);
});

您还可以使用并行承诺来提高效率。

云代码中没有断点,这使得 Parse 很难使用。唯一的方法是记录你的变量console.log

于 2014-11-10T03:56:53.613 回答
0

正如 knshn 所建议的那样,我能够利用 Promise 来实现它,以便我的代码在运行成功之前完成。

Parse.Cloud.job("updateQuestionAgreementCounts", function(request, status) {
    Parse.Cloud.useMasterKey();
    var promises = [];  // Set up a list that will hold the promises being waited on.
    var query = new Parse.Query("Question");
    query.each(function(question) {
        var agreementQuery = new Parse.Query("QuestionAgreement");
        agreementQuery.equalTo("question", question);
        agreementQuery.equalTo("agreement", 1);

        // Make sure that the count finishes running first!
        promises.push(agreementQuery.count().then(function(count) {
            question.set("agreementCount", count);

            // Make sure that the object is actually saved first!
            promises.push(question.save(null, null));
        }));
    }).then(function() {
        // Before exiting, make sure all the promises have been fulfilled!
        Parse.Promise.when(promises).then(function() {
            status.success("Finished updating Question Agreement Counts.");
        });
    });
});
于 2014-11-10T22:27:52.327 回答