循环中的多个查询解析云代码

时间:2015-03-19 19:55:19

标签: javascript parse-platform promise cloud-code

我很难理解承诺,我确定我需要使用它们,但我不知道如何和其他答案根本无法帮助我。

我想循环一个数组,查询数组中每个值的所有结果,然后在计算这些结果的平均值之后,在数组中添加平均值。在每次迭代之后,该数组作为响应发送。

这是我的代码,可以帮助我理解我:

Parse.Cloud.define('getScorePeopleArray', function(request, response) {

    var peopleArray = request.params.peoplearray;
    var query = new Parse.Query("Scores");
    var resultat;
    var index, len;
    var resultarray = [];
    var people;

    for (index = 0, len = peopleArray.length; index < len; ++index) {
      people = peopleArray[index];
      query.equalTo("People",people);
      query.find({
        success: function(results) {
          var sum = 0;
          for (var i = 0; i < results.length; ++i) {
           sum += results[i].get("Score");
          }
          resultat = (sum / results.length)*5;
          if(!resultat){
            resultarray.push("null");
          }else{
            resultarray.push(resultat);
          }
        },
        error: function() {
          response.error("score lookup failed");
        }
    }).then();
  }
  response.success(resultarray);  
});

当然,每次查询完成后都不会调用response.success,但是会尽快(因为如果我是正确的话,查询是异步的)。 我知道我必须用承诺改变它,但我完全不明白它是如何工作的。

提前多多感谢!

1 个答案:

答案 0 :(得分:12)

var _ = require('underscore');

Parse.Cloud.define('getScorePeopleArray', function(request, response) {

 var peopleArray = request.params.peoplearray; // what is this an array of?
 var resultArray = [];

  return Parse.Promise.as().then(function() { // this just gets the ball rolling
    var promise = Parse.Promise.as(); // define a promise

    _.each(peopleArray, function(people) { // use underscore, its better :)
      promise = promise.then(function() { // each time this loops the promise gets reassigned to the function below

        var query = new Parse.Query("Scores");
        query.equalTo("People", people); // is this the right query syntax?
        return query.find().then(function(results) { // the code will wait (run async) before looping again knowing that this query (all parse queries) returns a promise. If there wasn't something returning a promise, it wouldn't wait.

          var sum = 0;
          for (var i = 0; i < results.length; i++) {
            sum += results[i].get("Score");
          }
          var resultat = (sum / results.length) * 5;

          if (!resultat){
            resultArray.push("null");
          } else {
            resultArray.push(resultat);
          }

          return Parse.Promise.as(); // the code will wait again for the above to complete because there is another promise returning here (this is just a default promise, but you could also run something like return object.save() which would also return a promise)

        }, function (error) {
          response.error("score lookup failed with error.code: " + error.code + " error.message: " + error.message);
        });
      }); // edit: missing these guys
    });
    return promise; // this will not be triggered until the whole loop above runs and all promises above are resolved

  }).then(function() {
    response.success(resultArray); // edit: changed to a capital A
  }, function (error) {
    response.error("script failed with error.code: " + error.code + " error.message: " + error.message);
  });
});