我正在用Parse's Cloud Code編寫一個函數,用5張撲克牌填充服務器。這個想法是,服務器應該等到所有5張卡片都在數據庫中,然後才能進入功能的下一部分(目前它只是向控制檯輸出一條消息。)我的承諾是否按預期工作?
我所看到的是所有5卡被添加到數據庫中,也並不一定出現在序列數據庫中,這使我相信他們是正確的被異步補充說。而對於mostpart我的記錄顯示預期行爲。
I2015-01-03T17:08:01.244Z] Attempting to create cards x5
I2015-01-03T17:08:01.245Z] Attempting to save card0
I2015-01-03T17:08:01.247Z] Attempting to save card1
I2015-01-03T17:08:01.248Z] Attempting to save card2
I2015-01-03T17:08:01.249Z] Attempting to save card3
I2015-01-03T17:08:01.250Z] Attempting to save card4
I2015-01-03T17:08:01.352Z] Card saved:4
I2015-01-03T17:08:01.353Z] Card saved:4
I2015-01-03T17:08:01.354Z] Card saved:4
I2015-01-03T17:08:01.355Z] Card saved:4
I2015-01-03T17:08:01.356Z] Card saved:4
I2015-01-03T17:08:01.357Z] ALL 5 Promises theoretically fulfilled
然而,請注意,當卡實際保存時,其中每個卡的日誌都使用相同的編號 - 在此情況下,「卡已保存:4」。
問題是......我的承諾是否按預期工作?以及如何修復我的錯誤以顯示已保存的實際卡號?
這裏是我的代碼:
Parse.Cloud.define("populateServer", function(request, response)
{
console.log("Attempting to create cards x5");
var promises = createCards(5);
Parse.Promise.when(promises).then(function(result)
{
console.log("ALL 5 Promises theoretically fulfilled");
});
});
function createCards(qty)
{
var promises = [];
for (i=0;i<qty;i++)
{
var Card = Parse.Object.extend("Card");
var card = new Card();
card.set("name", "test");
card.set("number", i);
console.log("Attempting to save card" +i);
var promise = card.save();
promises.push(promise);
promise.then(function() {
console.log("Card saved:" +i);
}, function(error) {
console.log("Uh oh, something went wrong.");
});
}
return promises;
}
謝謝!我不知道如何創建承諾鏈並在循環中使用它們,這非常有用! –