如何在beforeSave和afterSave触发器中在parse.com中使两个查询原子化

时间:2016-01-29 09:22:26

标签: parse-platform triggers atomic

我在解析User(默认情况下)和UserData中创建了两个类。 BeforeSave触发如下:

Parse.Cloud.beforeSave(Parse.User, function(request, response) {
var userDataObject = new Parse.Object("UserData");
var fromUserPointer = {"__type":"Pointer","className":"_User","objectId":request.object.id}; 

return userDataObject.save({score: 0, ideasCount: 0, followersCount:0, return:0}).then(function (userData) {
    var userDataPointer = {"__type":"Pointer","className":"UserData","objectId":userData.id};
    request.object.set("userData", userDataPointer);
    response.success();
}, function(error) {
    response.error(error.message);
});

});

它保存用户的UserData并获取其UserData指针字段并保存在UserData类中。

Parse.Cloud.afterSave(Parse.User, function(request) {   
Parse.Cloud.useMasterKey();
var userPointer = {"__type":"Pointer","className":"_User","objectId":request.object.id};
var userData = request.object.get("userData");
if (userData) {
    var userDataPointer = {"__type":"Pointer","className":"UserData","objectId":userData.id};
    var userDataQuery = new Parse.Query("UserData");
    userData.set("user", userPointer);
    return userData.save().then (function (userData) {
        var activityObject = new Parse.Object("Activity");
        return activityObject.save({fromUserData: userDataPointer, from:userPointer, 
            toUserData:userDataPointer, to:userPointer, type:"follow"});
    }).then (function (success) {

    }, function (error) {
        console.error("Error in afterSave(user) : " + request.object.id + ":" + error.message);
    });     
}

});

问题是,在保存User类之前,它有时不会创建它应该创建的UserData。因此,这两个触发器必须以原子方式运行,而它们则不是。

0 个答案:

没有答案