我想在Parse中更新类中的多行。我需要使用“set”添加一个新字段。我并行尝试saveAll
和Promises
进行更新,但这些都是异步的。因此他们消耗了大量的资源和带宽。
如何以同步方式完成此操作。如果你能用系列中的承诺回答
,对我来说会更好这是我目前正在使用的代码。但我需要以一系列方式
Parse.Cloud.define("Updating",function(request,response){
var query = new Parse.Query("FollowUp");
query.find({
success: function(results){
for (var i = 0; i < results.length; i++) {
results[i].set("testfield","sometext");
}
Parse.Object.saveAll(results,{
success: function(list){
response.success("ok");
},
error: function(error){
response.error("failed");
}
});
},
error: function(error) {}
});
});
答案 0 :(得分:1)
此代码工作正常,并且是同步的。
Parse.Cloud.define("Updating",function(request,response){
var query = new Parse.Query("FollowUp");
query.find().then(function(results) {
var promise = Parse.Promise.as();
_.each(results, function(result) {
// For each item, extend the promise with a function to save it.
result.set("newfield","somevalue");
promise = promise.then(function() {
// Return a promise that will be resolved when the save is finished.
return result.save();
});
});
return promise;
}).then(function() {
response.success("working!!");
// Every object is updated.
});
});
或者您甚至可以使用“for”循环而不是_.each
Parse.Cloud.define("Updating",function(request,response){
var query = new Parse.Query("FollowUp");
query.find().then(function(results) {
var promise = Parse.Promise.as();
for(var i=0;i<results.length;i++){
results[i].set("newfield","somevalue");
promise = promise.then(function() {
// Return a promise that will be resolved when the save is finished.
return results[i].save();
});
});
return promise;
}).then(function() {
response.success("working!!");
// Every object is updated.
});
});