解析承诺以更新多行

Parse Promise to update multiple rows

本文关键字:更新 承诺      更新时间:2023-09-26

我想在 Parse 中更新一个类中的多行。我需要使用"set"添加一个新字段。我尝试并行saveAllPromises进行更新,但这两者都是异步的。因此,它们会消耗大量资源和带宽。

我怎样才能以同步的方式做到这一点。如果你能用串联的承诺来回答,对我来说会更好

这是我目前使用的代码。但我需要以系列方式

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) {}
    });
});

此代码工作正常,并且是同步的。

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.
});
});