循环中有许多删除的云代码,但response.success在parse.com上首先完成

时间:2014-03-12 15:14:29

标签: for-loop cloud parse-platform destroy

我有一个查询,他们查询可能会返回很多项目。 我可以通过所有这些并摧毁它们。

问题是因为destroy是Async,response.success(); part在执行所有销毁之前执行,因此并非所有项都被删除。

如何让它等到循环完成然后只有response.success();

感谢。

garageQuery2.find({
              success: function(results) {
                alert("Successfully retrieved " + results.length + " garages to delete.");
                // Do something with the returned Parse.Object values
                for (var i = 0; i < results.length; i++) { 
                  var object = results[i];
                  object.destroy({
                      success: function(myObject) {
                        // The object was deleted from the Parse Cloud.
                      },
                      error: function(myObject, error) {
                        // The delete failed.
                        // error is a Parse.Error with an error code and description.
                      }
                    });
                }

                response.success();
              },
              error: function(error) {
                alert("Error: " + error.code + " " + error.message);
              }
            });

1 个答案:

答案 0 :(得分:1)

尝试使用Promises

此代码基于:https://www.parse.com/docs/js_guide#promises-series

garageQuery2.find().then(function(results) {
  // Create a trivial resolved promise as a base case.
  var promiseSeries = Parse.Promise.as();
  // the "_" is given by declaring "var _ = require('underscore');" on the top of your module. You'll use Underscore JS library, natively supported by parse.com
  _.each(results, function(objToKill) {
    // For each item, extend the promise with a function to delete it.
    promiseSeries = promiseSeries.then(function() {
      // Return a promise that will be resolved when the delete is finished.
      return objToKill.destroy();
    });
  });
  return promiseSeries;

}).then(function() {
  // All items have been deleted, return to the client
  response.success();
});

希望有所帮助