Parse.com: query.each executes in parrallel, reaches limit

霸气de小男生 提交于 2020-01-01 17:01:11

问题


I am running a batch job and I would like them to be run serially for each query result The problem is that it seems that query.each executes everything in parrallel

How can I change my code to have everything execute serially?

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:


Both query.each and Parse.Cloud.run return a promise, so you can simply write as following:

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


来源:https://stackoverflow.com/questions/27191542/parse-com-query-each-executes-in-parrallel-reaches-limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!