我正在编写一个云代码函数,用于在删除对象后运行许多任务。 如何干净利落地完成这项工作?
您可以并行运行任务,也可以顺序运行它们?如果是这样,怎么样?
这是我的代码,你可以帮我清理/改变吗?
Parse.Cloud.afterDelete("Photo", function(request) {
Parse.Cloud.useMasterKey();
//delete all related activities
var queryAct = new Parse.Query("Activity");
queryAct.equalTo("photo",{
__type: "Pointer",
className: "Photo",
objectId: request.object.id
});
queryAct.limit(1000);
queryAct.find({
success: function(activities) {
Parse.Object.destroyAll(activities, {
success: function() {
//delete all related hashtags
var queryTags = new Parse.Query("hashTags");
queryTags.equalTo("photo",{
__type: "Pointer",
className: "Photo",
objectId: request.object.id
});
queryTags.limit(1000);
queryTags.find({
success: function(hashtags) {
Parse.Object.destroyAll(hashtags, {
success: function() {},
error: function(error) {
console.error("Error deleting related hashtags " + error.code + ": " + error.message);
}
});
},
error: function(error){
console.error("Error finding related hashtags " + error.code + ": " + error.message);
}
});
},
error: function(error) {
console.error("Error deleting related activities " + error.code + ": " + error.message);
}
});
},
error: function(error) {
console.error("Error finding related activities " + error.code + ": " + error.message);
}
});
});
感谢所有人!
答案 0 :(得分:1)
这里find.then.delete是一系列连续的任务。但是,您可以并行删除hastags
和activities
,因为它们似乎并非依赖。有关详细信息,请查看promises guide。
您的代码可以缩短如下:
var Photo = Parse.Object.extend("Photo");
Parse.Cloud.afterDelete("Photo", function(request) {
Parse.Cloud.useMasterKey();
var photo = Photo.createWithoutData(request.object.id);
var queryAct = new Parse.Query("Activity");
queryAct.equalTo("photo", photo);
queryAct.limit(1000);
var promiseForActivities = queryAct.find().then(function (activities) {
return Parse.Object.destroyAll(activities);
});
var queryTags = new Parse.Query("hashTags");
queryTags.equalTo("photo", photo);
queryTags.limit(1000);
var promiseForHashtags = queryTags.find().then(function (hashtags) {
return Parse.Object.destroyAll(hashtags);
});
return Parse.Promise.when([promiseForActivities, promiseForHashtags]).then(function () {
console.log("Done");
}, function (err) {
console.error(err);
});
});
请注意,您不需要创建自己的指针对象,如:
{
__type: "Pointer",
className: "Photo",
objectId: "someId"
}
相反,您可以使用createWithoutData这是一个快捷方式:
var Photo = Parse.Object.extend("Photo");
var p = new Photo();
p.id = "someId";
我也认为直接传递request.object
就足够了,例如queryAct.equalTo("photo", request.object);