2015-04-03 68 views
0

我正在使用Parse和服務器端Javascript。如下所示,我想在我的列職責中保存總數。這段代碼保存了新的列的職責,但它沒有給它賦值。 Total總是混合了真實值和虛假值(如0和NaN),因爲每個Id都沒有Total。保存嘗試保存字段/列但不包含值

for (i = 0; i < Ids.length; i++){ 
Id = Ids[i]; 

var Total = Math.round(_.reduce(_.map(value[i], function (n) { 
    return n.Partial 
    }), function (memo, num) { 
    return memo + num; 
    }, 0) * 100)/100; 


Query.get(Id, { 
success: function (item) { 
    item.set("duty", Total); 
    Q.all(item.save()); 
    } 
}) 
} 
+0

什麼是'Q.all'? – Bergi 2015-04-03 10:38:38

+0

https://github.com/kriskowal/q這是一個承諾庫。我可能會錯誤地使用它。 。 。 – rashadb 2015-04-04 04:47:25

+0

好的,我可以猜到,只有我會預料到你會使用Parse諾言。是的,除非'item.save()'返回一個數組,否則你使用它是錯誤的。 – Bergi 2015-04-04 11:31:10

回答

1

試圖重構一點,(沒有完全理解代碼的含義)。分成邏輯部分時變得更清晰。異步發生的事物總是被分成承諾返回函數。

它最終在savePromises的陣列中,它可以與saveAll一起運行。

var savePromises = []; 
_.each(Ids, function(objectId, index) { 
    savePromises.push(setDuty(objectId, index)); 
}); 
Parse.Object.saveAll(savePromises); 

// get an object with its id. use its index to compute a duty 
// return a promise to save the object 
function setDuty(objectId, index) { 
    return getObjectWithId(objectId).then(function(object) { 
     object.set("duty", dutyValueForIndex(index)); 
     return object.save(); 
    }); 
} 

// return a promise to get an object with its id 
function getObjectWithId(objectId) { 
    var query = new Parse.Query("Table_Name_Goes_Here"); 
    return query.get(objectId); 
} 

// compute duty for a given index 
function dutyValueForIndex(index) { 
    var array = _.map(value[i], function(n) { 
     return n.Partial 
    }); 
    var sum = _.reduce(array, function(memo, num) { return memo+num; }, 0); 
    return sum * 100/100; 
} 
+0

謝謝!我現在只是看到了這個,所以我會看看並跟進 – rashadb 2015-04-04 04:47:41

+0

謝謝Danh,你的方法是無與倫比的。我在尋找錯誤方面得到了一些幫助:Parse :: UserCannotBeAlteredWithoutSessionError你知道該怎麼做嗎?我在表達和在這個JS文件的頂部我有var Parse = require('parse')。 Parse.initialize(「JS key」,「Application Key」,「Master Key」); – rashadb 2015-04-04 05:15:53

+0

UserCannotBeAlteredWithoutSessionError表示代碼嘗試在沒有用戶的情況下寫入_User行。默認情況下,用戶表被設置爲只有用戶可以修改他或她自己的記錄。由於這是雲代碼,因此快速解決此問題的方法是Parse.Cloud.useMasterKey()。 (請參閱https://parse.com/questions/getting-usercannotbeateredwithsessionerror) – danh 2015-04-04 18:39:46