Prime_Coder
Prime_Coder

Reputation: 161

cloud code multiple save then response success

I have a Game class and GamePlayer class in the Parse app database, where users play game and win coins.

In my cloud code function, I have the following code

success : function(results) {
   Parse.Cloud.useMasterKey();
   if (results.length >= 2) {
       console.log("inside find query1 success.");

       for (var i = 0; i < object.length; i++) {
          if (i == 0) {
             results[0].set("finish_msg", "You won!");
             results[0].attributes.playerId.set("coins", (results[0].attributes.playerId.attributes.coins + 10) );
          } else if (i == 1) {
             results[1].set("finish_msg", "You won!");
             results[1].attributes.playerId.set("coins", (results[1].attributes.playerId.attributes.coins + 5) );
          } else {
             object[i].set("finish_msg", "You lost!");
          }

          object[i].save();
       }

      response.success({
            "result" : true
      });
   }
}

Here, playerId is a pointer to the User table, I'm increasing the first and second user's coins by 10 and 5 respectively.

What I want to do is set all user's finish message status (either win / lost) and after save send the success response to the client. Here the save process takes some time. How to wait for the save process to complete?

Currently, sometimes this code works, sometimes not. Particularly, when the results length is more than 3.

Please suggest how can I change the code to work correctly.

Upvotes: 1

Views: 138

Answers (1)

danh
danh

Reputation: 62676

object[i].save() runs asynchronously, and response.success() halts anything in progress. So the early saves finish while the next few are being started, then everything is stopped when the loop finishes.

The way around this is with promises...

var promises = [];
for (var i = 0; i < object.length; i++) {

    // ... your for-loop code

    // add a promise to save to the array of promises
    promises.push(object[i].save());
}
// return a promise that is fulfilled when all the promises in the array are fulfilled
Parse.Promise.when(promises).then(function() {
    // all of the saved objects are in 'arguments'
    response.success({result:true});
}, function(error) {
    response.error(error);  // return errors, too, so you can debug
});

Upvotes: 1

Related Questions