解析云代码嵌套.each查询

时间:2016-02-11 20:39:34

标签: javascript parse-platform

我在Parse Cloud中使用以下代码几天了。我知道我对嵌套查询做错了,但尝试了很多但仍然无法正常工作。

第一个代码正在运行,但未创建分类帐对象。

我应该在这里使用承诺吗? 感谢您的高级帮助。

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 个答案:

答案 0 :(得分:1)

是。您应该使用Promises来确保在返回之前保存循环中的所有用户。像这样:

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 */ });