云码多次保存响应成功
cloud code multiple save then response success
我在 Parse 应用程序数据库中有一个游戏 class 和 GamePlayer class,用户可以在其中玩游戏并赢取金币。
在我的云代码函数中,我有如下代码
success : function(results) {
Parse.Cloud.useMasterKey();
if (results.length >= 2) {
console.log("inside find query1 success.");
for (var i = 0; i < object.length; i++) {
if (i == 0) {
results[0].set("finish_msg", "You won!");
results[0].attributes.playerId.set("coins", (results[0].attributes.playerId.attributes.coins + 10) );
} else if (i == 1) {
results[1].set("finish_msg", "You won!");
results[1].attributes.playerId.set("coins", (results[1].attributes.playerId.attributes.coins + 5) );
} else {
object[i].set("finish_msg", "You lost!");
}
object[i].save();
}
response.success({
"result" : true
});
}
}
这里,playerId 是指向用户的指针table,我将第一个和第二个用户的硬币分别增加 10 和 5。
我想做的是设置所有用户的完成消息状态(赢/输)并在保存后将成功响应发送给客户端。这里的保存过程需要一些时间。如何等待保存过程完成?
目前,此代码有时有效,有时无效。特别是当结果长度大于 3 时。
请建议我如何更改代码才能正常工作。
object[i].save()
异步运行,response.success()
停止任何正在进行的操作。所以早期的保存在接下来的几个开始时完成,然后在循环结束时一切都停止。
解决这个问题的方法是承诺...
var promises = [];
for (var i = 0; i < object.length; i++) {
// ... your for-loop code
// add a promise to save to the array of promises
promises.push(object[i].save());
}
// return a promise that is fulfilled when all the promises in the array are fulfilled
Parse.Promise.when(promises).then(function() {
// all of the saved objects are in 'arguments'
response.success({result:true});
}, function(error) {
response.error(error); // return errors, too, so you can debug
});
我在 Parse 应用程序数据库中有一个游戏 class 和 GamePlayer class,用户可以在其中玩游戏并赢取金币。
在我的云代码函数中,我有如下代码
success : function(results) {
Parse.Cloud.useMasterKey();
if (results.length >= 2) {
console.log("inside find query1 success.");
for (var i = 0; i < object.length; i++) {
if (i == 0) {
results[0].set("finish_msg", "You won!");
results[0].attributes.playerId.set("coins", (results[0].attributes.playerId.attributes.coins + 10) );
} else if (i == 1) {
results[1].set("finish_msg", "You won!");
results[1].attributes.playerId.set("coins", (results[1].attributes.playerId.attributes.coins + 5) );
} else {
object[i].set("finish_msg", "You lost!");
}
object[i].save();
}
response.success({
"result" : true
});
}
}
这里,playerId 是指向用户的指针table,我将第一个和第二个用户的硬币分别增加 10 和 5。
我想做的是设置所有用户的完成消息状态(赢/输)并在保存后将成功响应发送给客户端。这里的保存过程需要一些时间。如何等待保存过程完成?
目前,此代码有时有效,有时无效。特别是当结果长度大于 3 时。
请建议我如何更改代码才能正常工作。
object[i].save()
异步运行,response.success()
停止任何正在进行的操作。所以早期的保存在接下来的几个开始时完成,然后在循环结束时一切都停止。
解决这个问题的方法是承诺...
var promises = [];
for (var i = 0; i < object.length; i++) {
// ... your for-loop code
// add a promise to save to the array of promises
promises.push(object[i].save());
}
// return a promise that is fulfilled when all the promises in the array are fulfilled
Parse.Promise.when(promises).then(function() {
// all of the saved objects are in 'arguments'
response.success({result:true});
}, function(error) {
response.error(error); // return errors, too, so you can debug
});