解析JavaScript SDK并保证链接

时间:2014-12-31 15:32:34

标签: javascript parse-platform promise cloud-code

我在Parse Cloud Code中创建了一个后台作业,它根据我的一个Parse类中的日期发送电子邮件通知。

这是一个想法:查询包含日期的类。迭代返回的每个对象并检查日期字段。如果日期等于今天,发送电子邮件通知,将日期更改为null并将其保存回Parse。

但是,似乎并非所有对象都保存回Parse。我怀疑这是我的承诺链的问题,但我很难诊断确切的问题或如何解决它。以下是相关代码

Parse.Cloud.job("job", function(request, status) {


// Query for all users
var query = new Parse.Query(className);
query.each(function(object) {

    if (condition) {

        object.set(key, false);
        object.save(null, {
            success:function(object){
                // This never executes!
            },
            error: function(error){

            }

        }).then(function(){
            // This never executes
            console.log("Save objects successful");
        },
        function(error){
            status.error("Uh oh, something went wrong saving object");
        });

        // Set hiatus end successful
        Mailgun.sendEmail({
        });
    }

    });
});

objects.save()promise链中的这一行console.log("Save objects successful");永远不会被执行 - 即使订阅对象成功保存到Parse。

此外,如果查询返回的对象超过5个,则只有前5个成功保存回Parse。不会执行任何其他保存,也不会发送电子邮件通知。

1 个答案:

答案 0 :(得分:6)

我按照以下方式清理它,依靠Promise.when ......

var savePromises = [];  // this will collect save promises 
var emailPromises = [];  // this will collect email promises 

// your code to setup the query here
// notice that this uses find() here, not each()
query.find(function(subscriptions) {
    _.each(subscriptions, function(subscription) { // or a for loop, if you don't use underscore

        // modify each subscription, then
        savePromises.push(subscription.save());

        // prepare each email then
        var emailPromise = Mailgun.sendEmail({ /* your email params object here */ });

        emailPromises.push(emailPromise);
    });
    // now do the saves
    return Parse.Promise.when(savePromises);
}).then(function() {
    // now do the emails
    return Parse.Promise.when(emailPromises);
}).then(function() {
    // Set the job's success status
    status.success("Subscriptions successfully fetched");

// and so on with your code

您可能还会考虑将保存和电子邮件组合成一大堆承诺,但由于它们具有不同的故障模式,因此最好连续两批进行。