解析云代码 - 从指针数组中删除指针

时间:2014-10-11 13:09:24

标签: javascript parse-platform cloud-code

删除标记时,我正在使用Parse云代码清除指向“Tag”对象的所有指针。 “beforeDelete”被调用,我没有得到任何错误+控制台打印正确的“歌曲”对​​象“指向已删除的”标签“。

但是指针不会从数组中删除。

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);
          }
     });
});

我做错了什么?

由于 沙尼

1 个答案:

答案 0 :(得分:6)

object.save();是异步的。在保存操作完成之前,您正在调用response.success()。您可以使用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);
});

或者您可以使用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);
});