Reputation: 147
I have been developing a mock up android app and want to write Parse Background job.
My Parse users are customers and I sell
services that customers can subscribe to. The _User
class is for customers and the CustomerSubscriptions
class is for subscriptions.
I'm trying to update all the customers' bills but I can't.
Can some one steer me in the right direction?
Thanks
Parse.Cloud.job("billCustomers", function(request, response) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query(CustomerSubscriptions);
var array = new Array();
//For each registered user
query.find().then(function(results) {
for (var i = 0; i < results.length; ++i) {
var username = results[i].get("username");
array[username] = results[i].get("Price");
}
var query2 = new Parse.Query(Parse.User);
return query2.find();
}).then(function(results) {
for (var i = 0; i < results.length; ++i) {
var username = results[i].get("username");
results[i].set("Bill",array[username]);
results[i].save();
}
}, function(error) {
response.error("Error");
});
});
Upvotes: 1
Views: 437
Reputation: 2906
The problem is in results[i].save();
That is an async operation. Your function is most likely returning before all of the saves are complete. I would collect all of your promises in an array and then use Parse.Promise.when to return once they are all complete. You'll also want to call response.success() when you're done.
Try something like this:
.then(function(results) {
var savePromises = []; // this will collect save promises
_.each(results, function(result) { // or a for loop, if you don't use underscore
var username = result.get("username");
result.set("Bill",array[username]);
savePromises.push(result.save());
});
// now do the saves
return Parse.Promise.when(savePromises);
}, function(error) {
response.error();
}).then(function() {
// this should execute once all the saves are done
// Set the job's success status
response.success("saves completed");
});
I'm using underscore to iterate through the results array.
Upvotes: 1