Promises On Cloud Code
I'm writing a cloud code function for run many task after delete an object. How can I do this cleanly and without nesting? You can run tasks in parallel or it is better to have th
Solution 1:
Here find.then.delete is a series of tasks in a row. However, you can delete your hastags
and activities
in parallel since they don't seem to be dependent. Please check promises guide for more info.
Your code can be shortened as below:
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);
});
});
Note that you don't need to create your own pointer objects like:
{
__type: "Pointer",
className: "Photo",
objectId: "someId"
}
Rather you can use createWithoutData which is a shortcut for:
var Photo = Parse.Object.extend("Photo");
var p = new Photo();
p.id = "someId";
I also think that it could be enough to pass the request.object
directly, like queryAct.equalTo("photo", request.object);
Post a Comment for "Promises On Cloud Code"