Search code examples
for-loopcloudparse-platformdestroy

Cloud code with many deletes in loop, but response.success finishes first on parse.com


I have a query, and they query may return many items. I can go through all of them and destroy them.

The problem is since destroy is Async, the response.success(); part is executed before all the destroys are executed, so not all items are really deleted.

How can I make it wait until the loop is done and then only response.success();

Thanks.

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

Solution

  • Try to work with Promises

    This code is based on this: 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();
    });
    

    Hope it helps