Search code examples
parse-platformpush-notificationparse-cloud-code

can't execute query.find() in my cloud code


I have a cloud code that fetch data from 'Core' & HTTP API and do some logic on it. Now I want to send push notification based on the result but the code doesn't even getting executed here is a snippet of code

.then(function(result) {
  for (var i = 0; i < queryObjects.length; i++) {
    var object = queryObjects[i];

    console.log('This will loop for '+queryObjects.length+' times');

    var pushQuery = new Parse.Query(Parse.Installation);
    pushQuery.equalTo('installationID',object.get('installationID'));
    pushQuery.equalTo('deviceType','ios');
    Parse.Push.send({ 
      where: pushQuery,
      data: {
          alert: "When do we take to outer space",
          badge: "Increment"
        }
      }, {
        success: function() {
          console.log("Push was successful");
        },
        error: function(error) {
          console.error(error);
        }
    });
  }

Even If I tried to execute query.find() nothing happened

.then(function(result) {
      for (var i = 0; i < queryObjects.length; i++) {
        var object = queryObjects[i];

        console.log('This will loop for '+queryObjects.length+' times');

        var pushQuery = new Parse.Query(Parse.Installation);
        pushQuery.equalTo('installationID',object.get('installationID'));
        pushQuery.equalTo('deviceType','ios');
        pushQuery.find({
          success:function(list) {
            console.log("Query Data: "+list);
          },
          error: function(error) {
            console.log("Error: " + error.code + " " + error.message);
          }
        });
      }

Solution

  • This is because of the asynchronous nature of Push.Send function. You are calling it multiple times in a loop but you do not wait for any of those calls to finish before returning from the .then block. You need to know that when a Pasre asynchronous function returns, it is not necessarily finished. You need to wait on its Promise to be fulfilled just to make sure it has completed.

    You can change your code to make sure that you call Parse.Push function only once (in your Installation query, use containedIn constraint on the array of your installationIDs you build in the loop and call Parse.Push only once after the loop and make sure to return its Promise.

    The other solution is that for each time you call a Parse.Push function in the loop, you need to push them in an array of promises and then wait for all of them to finish using Parse.Promise.when(promises);. The documentation is very clear on how to wait on Promises in parallel.