I'm writing a function in Parse's Cloud Code which populates the server with 5 playing cards. The idea being that the server should wait until all 5 cards are in the database before moving on to the next part of the function (which currently just outputs a message to the console.
What I'm seeing is that all 5 cards are being added to the database. They also do not necessarily appear in the database in sequence, which makes me believe they are correctly being added asynchronously. And for the mostpart my logging shows intended behaviour.
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
However, notice that when the cards are actually saved, the log for each one of them is using the same number - in this case "Card saved:4".
Question is... are my promises working as intended? and how do I fix my bug to show the actual card number that was saved?
Here's my code:
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;
}
Aucun commentaire:
Enregistrer un commentaire