0

tI'm a few days stuck with my following code in Parse Cloud. I know i'm doing the nested query wrong, but tried a lot and still doesn't get it working.

The first code is working, but the ledger object is not created.

Should i use promises here? Thanks for your help in advanced.

Parse.Cloud.job("PayTax", function(request, status) {

var promises = []; // promises array
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.each(function(user) {
      // Set and save the change
    var balance = user.get("balance");
    var stamount = user.get("streets");
    var level = user.get("level");
    var tax = 5 * level * stamount;
    var newbalance = balance - tax;

    user.set("balance", newbalance);
    user.save();
    console.log("User tax payed " + tax + " " + user.get("username") + "ID: " + user.id); 

        //update ledger // 2nd query
        var Ledger = Parse.Object.extend("Ledger");
        var ledger = new Ledger();

        var userPointer = new Parse.Object("_User");
        userPointer.id = user.id;

        ledger.set("type", "tax");
        ledger.set("amount", tax);
        ledger.set("user", user);
        ledger.set("description", "Tax payed");
        ledger.set("xp", 0);
        console.log("Tax added to Ledger " + tax + user.get("username") + "ID: " + user.id); 
        promises.push(ledger.save());

});Parse.Promise.when(promises).then(function() {
        // Set the job's sucess status   
        status.success("Update balance completed successfully.");

}, function(error) {
    // Set the job's error status
        status.error("Uh oh, something went wrong." + error);
});

});

1 Answer 1

1

Yes. You should use Promises to ensure all the users in the loop are saved before returning. Something like this:

var promises = []; // promises array
promises.push(ledger.save()); // push every save in an array
// Then wait for all of them to finish in parallel
Parse.Promise.when(promises).then(function() { /* all saves done */ }); 
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Mo Nazemi, thanks for your help. I've still not managed to get it working. I've updated my code, what am I doing wrong?
query.each function has to end before waiting on those promises.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.