【问题标题】:Multiple queries in a loop Parse Cloud Code循环中的多个查询解析云代码
【发布时间】:2015-03-19 19:55:18
【问题描述】:

我很难理解承诺,我确定我需要为此使用它们,但我不知道如何,其他答案对我一点帮助都没有。

我想遍历一个数组,查询数组每个值的所有结果,然后计算这些结果的平均值后,将平均值添加到数组中。每次迭代后,都会将此数组作为响应发送。

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

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 不会在每个查询完成时调用,而是尽快调用(因为如果我是对的,查询是异步的)。 我知道我必须用承诺来改变它,但我完全不明白这是如何工作的。

提前非常感谢!

【问题讨论】:

标签: javascript parse-platform promise parse-cloud-code


【解决方案1】:
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);
  });
});

【讨论】:

  • 太棒了,谢谢!编辑:我还会检查其他人的链接,以更好地了解 Promise 是如何工作的,它看起来真的很强大
  • 忘记回答你关于cmets的问题了:数组是字符串数组,查询语法看起来是对的(查询中的人代表数组的每个对象对吧?)
  • 对不起,连续第三条消息,但我有一个错误:无法调用未定义的方法'then'。对于这些行:“return Parse.Promise.as().then(function() {...”和“.then(function() { response.success(resultarray);...”我正在研究它
  • 以为我刚刚修好了。缺少一个结束 });对此感到抱歉。
  • 仍然不适合我:失败:ReferenceError:resultarray 未在 Parse.js:2:4651 的 e (Parse.js:2:5101) 的 main.js:77:22 处定义在 Array.forEach (native) 在 Object.x.each.x.forEach [as _arrayEach] (Parse.js:1:665) 在 c.extend.resolve (Parse.js:2:4602) 在 Parse.js: 2:5181 at e (Parse.js:2:5101) at Parse.js:2:4651 at Array.forEach (native) 我尝试只使用查询和缓存策略来使其更快,所以不用担心如果它仍未解决这是您获取正确行号的粘贴箱:pastebin.com/jKYc2v7c
猜你喜欢
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多