Parse.com:query.each以parrallel方式执行,达到limit

时间:2014-11-28 15:14:26

标签: background parse-platform cloud-code

我正在运行一个批处理作业,我希望它们能够针对每个查询结果进行串行运行 问题是,query.each似乎在parrallel

中执行所有操作

如何更改代码以使所有内容按顺序执行?

Parse.Cloud.job("fetchMenus", function(request, status) {

  var counter = 0;
  // Query for all users
  var LocationSP = Parse.Object.extend("Location");
  var query = new Parse.Query(LocationSP);
  query.doesNotExist("menu");
  query.equalTo("city_lc","new york");
  // query.limit(10);
  var p = Parse.Promise.as("");

  query.each(function(location) {

    p = p.then(function(){

    if (counter % 100 === 0) {
        // Set the  job's progress status
        status.message(counter + " users processed.");
      }
    // console.log(location);
    // console.log(location.get("location_id"));

        Parse.Cloud.run('getMenu2', {alias: location.get("location_id") }, {
          success: function(result) {
            // result is 'Hello world!'
            counter += 1;
            return Parse.Promise.as("1");
          },
          error: function(error) {
            return Parse.Promise.as("1");
          }
        });
    })

    return p;


  }).then(function() {
    // Set the job's success status
    status.success("Migration completed successfully.");
  }, function(error) {
    // Set the job's error status
    status.error("Uh oh, something went wrong." + error);
  });
});

1 个答案:

答案 0 :(得分:2)

query.eachParse.Cloud.run都会返回一个承诺,因此您只需按以下方式编写:

Parse.Cloud.job("fetchMenus", function(request, status) {
  var LocationSP, counter, query;
  counter = 0;
  LocationSP = Parse.Object.extend("Location");
  query = new Parse.Query(LocationSP);
  query.doesNotExist("menu");
  query.equalTo("city_lc", "new york");
  return query.each(function(location) {
    if (counter % 100 === 0) {
      status.message(counter + " users processed.");
    }
    return Parse.Cloud.run('getMenu2', {
      alias: location.get("location_id")
    }).then(function(result) {
      counter += 1;
      return Parse.Promise.as("1");
    }, function(error) {
      return Parse.Promise.as("1");
    });
  }).then(function() {
    return status.success("Migration completed successfully.");
  }, function(error) {
    return status.error("Uh oh, something went wrong." + error);
  });
});