Victor Cooper
Victor Cooper

Reputation: 73

Parse Cloud Code Helper Function Not Working

Here is the parse javascript cloud code I wrote. I want to find all objects in subclass "Example" having one like and then reset them as four. I have already established the Example class and Like column in the data browser. But the query didn't work and I can't figure out why.

function exampleFunction() {
  var Example = Parse.Object.extend("Example");
  var newObject = new Example();
  newObject.save(); // until here, the function works, it continues creating new objects
  var query = new Parse.Query(Example);
  query.equalTo('Like',1);
  query.find({
    success:function(result){
      for (var i = 0; i < result.length; i++) {
          result[i].set('Like',4);
      }
    },
    error:function(error){

    }
  }) 
}

  Parse.Cloud.define("nice", function(request, response) {
      exampleFunction();
      response.success();
  });

I use this period of code on iOS device to trigger the cloud function:

[PFCloud callFunctionInBackground:@"nice"
                   withParameters:@{}
                            block:^(NSString *result, NSError *error) {
                                if (!error) {
                                }
                            }];

Upvotes: 0

Views: 701

Answers (1)

chasew
chasew

Reputation: 8828

A couple of possible issues..

  1. You are calling asynchronous methods and not giving them time to complete. That's where Parse Promises come in. You have to make sure to use the then function. See http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/
  2. You are correctly setting 'Like' to 4, but you aren't saving the rows by calling save
  3. You may not have any rows coming back from your query, they way to check that is to pass the number of rows found back through the success callback, which I am doing below

Try this below, noticing that the .success should return a result if you NSLog(@"result %@",result) from your objective-c. Also, the error should be coming through now as well because of response.error(error)

var Example = Parse.Object.extend("Example");

function exampleFunction() {
  var query = new Parse.Query(Example);
  query.equalTo('Like',1);
  return query.find().then(function(examplesLikedOnce){
    var promises = [];
    for (var i = 0; i < examplesLikedOnce.length; i++) {
      var example = examplesLikedOnce[i];
      var promise = example.save({Like:4});
      promises.push(promise);
    }
    return Parse.Promise.when(promises).then(function(){
      return examplesLikedOnce.length;
    });
  }); 
}

Parse.Cloud.define("nice", function(request, response) {
    exampleFunction().then(function(numExamples){
      response.success("The number of Example objects with 1 like: "+numExamples);
    }, function(error){
      response.error(error);
    });
});

Upvotes: 1

Related Questions