2

I am using Parse cloud code to clear all pointers to a "Tag" object when the tag is deleted. "beforeDelete" is called and I don't get any errors + The console prints the correct "Song" objects" that has the pointer to the deleted "Tag".

But the pointer is not removed from the Array.

Parse.Cloud.beforeDelete("Tag", function(request, response) {
    var query = new Parse.Query("Song");
    query.equalTo("tags", request.object);
    query.include(["tags"]);
     query.find({
           success: function(songs) {
              console.log(songs);
              for (var i = 0; i < songs.length; i++) {
                    songs[i].remove("tags",request.object);
                    songs[i].save();
              };
             response.success();

          },
          error: function(error) {
              response.error(error);
          }
     });
});

What am I doing wrong ?

Thanks Shani

shannoga
  • 19,649
  • 20
  • 104
  • 169

1 Answers1

6

object.save(); is asynchronous. You are calling response.success() before save operations finish. You can use query.each():

var query = new Parse.Query("Song");
query.equalTo("tags", request.object);
query.include("tags");
query.each(function (song) {
  song.remove("tags",request.object);
  song.save();      
}).then(function() {
  response.success();
}, function(error) {
  response.error(error);
});

Or you can use parallel promises

var _ = require("underscore");

var query = new Parse.Query("Song");
query.equalTo("tags", request.object);
query.include("tags");
query.find().then(function(songs) {
  var promises = [];
  _.each(songs, function(song) {
    song.remove("tags",request.object);
    promises.push(song.save());
  });
  // Return a new promise that is resolved when all of the saves are finished.
  return Parse.Promise.when(promises);

}).then(function() {
  response.success();
}, function(error) {
  response.error(error);
});
knshn
  • 3,401
  • 1
  • 21
  • 22
  • Thanks, missed that somehow. BTW " _.each(songs, function(song) {" is not working for some reason. But anyway it is working great now. – shannoga Oct 13 '14 at 16:15
  • Ah I forgot to mention that you need to add underscore library `var _ = require("underscore");` – knshn Oct 13 '14 at 16:17