在循环中有许多删除的云代码,但是响应.在parse.com上,成功首先结束



我有一个查询,他们的查询可能返回许多项。我可以把所有的人都干掉。

问题是由于destroy是异步的,response.success();部分在所有销毁操作执行之前执行,因此并非所有项都被真正删除。

我如何让它等待,直到循环完成,然后只有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);
              }
            });

尝试使用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();
});

希望有所帮助