Parse JavaScript SDK and Promise Chaining

Parse JavaScript SDK and Promise Chaining

本文关键字:Promise Chaining and SDK JavaScript Parse      更新时间:2023-09-26

我在 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() 承诺链中的这一行console.log("Save objects successful");永远不会被执行 - 即使订阅对象成功保存到 Parse 也是如此。

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

我会按如下方式清理它,依靠 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

您也可以考虑将保存和电子邮件合并到一个大的承诺数组中,但最好分两批连续进行,因为它们具有不同的失败模式。