Reputation: 168
I was working on a piece of cloud code (Parse) for my IOS application and noticed that it wouldn't work whenever I tried to save the updated object. If I remove the save function, the code works and prints out the the success response, but if I keep it in I get the error:
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
I've tried out a bunch of solutions and regardless of what they are, the error message above still gets printed from the X-Code debugger IF the save function is in the code. (If not then it prints the success response)
This is the code:
Parse.Cloud.define("removeFriend", function(request, response) {
Parse.Cloud.useMasterKey();
var userObjId = request.params.userObjId;
var currentUser = request.params.currentUser;
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", userObjId);
//query.include('Friends');
query.find({
success: function(results){
var friendsArray = (results[0].get("Friends"));
var newFriends = friendsArray.filter(function(x) {return x != currentUser});
results[0].set("Friends", newFriends);
results[0].save();
response.success("THIS IS RESULT" + results[0].get("Friends"));
},
error: function(){
response.error("The user was not successfully removed.");
}
});
});
(I created a similar question with the same error earlier but have redone the code since then so I didn't want to mix the two questions up.)
Upvotes: 0
Views: 177
Reputation: 4378
Saves are asynchronous, meaning they happen in a separate thread. You are returning with response.success()
right after calling save()
, so the save never completes before the function terminates.
You have two options: Add success / error options to the save()
call, or use promises. I prefer the latter, it enables much cleaner code when you get the hang of them.
results[0].save().then(
function( success ) {
response.success("THIS IS RESULT" + results[0].get("Friends"));
},
function( error ) {
response.error("There was an error trying to save the object: " + JSON.stringify(error));
}
);
Upvotes: 1