在云代码中使用javascript的嵌套查询(Parse.com)

时间:2013-11-04 21:12:09

标签: javascript parse-platform

是否可以在云代码中执行嵌套查询?

我希望能够做一些像

这样的事情
var adList = [];
var query2 = new Parse.Query("QR");
var query = new Parse.Query("Campaigns");
query.equalTo("isFeatured", true);

query.find({
success: function(results)  {
    for (var i=0; i<results.length; i++){
        var ad = [];
        ad.push(results[i].get("Type"));    //Adds "Type" to the ad array
        ad.push(results[i].id);     //gets the objectID and appends it to the arrayy

          //second INNER QUERY
        query2.equalTo("abc", true);
        adList.push(ad);
        query2.first({
            success: function(results){
                adList.push(5);
            },
            error: function(){
                response.error("inner fail");
            }
        });

    }

    response.success(adList);  //adds all ad arrays to adList array
},
error: function(){
    response.error("failed");
}   
});

我尝试过这样做,但内部查询永远不会执行。为什么呢?

3 个答案:

答案 0 :(得分:14)

第二个查询是异步的,因此将其包装在for中将无效。

response.success在第二个查询完成之前被触发,因此您在实际等待结果之前返回。我会告诉你将response.success移到success的第二个query2回调中,但由于您在for内同步运行异步操作,因此无效您将在第一个success发送回复。

不要在循环中运行异步操作。它不起作用。

我不确定你要在这里完成什么,但是如果你想做出与结果一样多的查询,你将不得不为每次通话实例化一个新的Query

同样,我不确定你到底想要做什么,但这是一种你可以这样做的方式:

    var adList = [];
    var query = new Parse.Query("Campaigns");
    query.equalTo("isFeatured", true);

    query.find({
        success: function(results)  {
            var queries = [];

            for (var i=0; i<results.length; i++){
                var query2 = new Parse.Query("QR");
                query2.equalTo("abc",true);

                var ad = [];
                ad.push(results[i].get("Type"));
                ad.push(results[i].id);
                adList.push(ad);
                queries.push(query2);
            }

            var totalLength = results.length;

            function makeQueries(qs){
                qs.shift().first({
                    success: function(currentResult) {
                        // do stuff with currentResult
                        if(qs.length){
                            makeQueries(qs);
                        } else {
                            console.log('We successfully made ' + totalLength + ' queries')
                            // we are done with the queries
                            response.success(adList);
                        }
                    },
                    error: function() {
                        response.error('Error in inner queries nº' + totalLength - qs.length)
                    }
                });
            }
            makeQueries(queries);
        },
        error: function(){
            response.error("failed");
        }
    });

请注意,Parse Cloud Code允许您运行aprox 5/7秒的代码,如果您有很多results,这可能会非常慢。 顺便说一句,看看Parse的matchesQuery方法。

从他们的文档中获取的示例:

    var Post = Parse.Object.extend("Post");
    var Comment = Parse.Object.extend("Comment");
    var innerQuery = new Parse.Query(Post);
    innerQuery.exists("image");
    var query = new Parse.Query(Comment);
    query.matchesQuery("post", innerQuery);
    query.find({
      success: function(comments) {
        // comments now contains the comments for posts with images.
      }
    });        

答案 1 :(得分:1)

我认为以下代码可能对某人有帮助,

var adList = [];
var query2 = new Parse.Query("QR");
var query = new Parse.Query("Campaigns");
query.equalTo("isFeatured", true);

query.find().then(function(results) {
    var _ = require('underscore');
    var promise = Parse.Promise.as();
    _.each(results, function(resultObj) { 
        var ad = [];
        ad.push(resultObj.get("Type"));    //Adds "Type" to the ad array
        ad.push(resultObj.id);     //gets the objectID and appends it to the arrayy

        //second INNER QUERY
        query2.equalTo("abc", true);
        adList.push(ad);
        return query2.first().then(function(results) {
            adList.push(5);
        });
    });
    return promise;
}).then(function() {
    response.success(adList);
}, function (error) {
    response.error("Error "+error.message);
});

答案 2 :(得分:0)

我能够拼凑出以下答案。这适合我。遵循并行承诺的parse.com文档指南。我创建了两个promise数组。其中一个用作内循环的promise数组。另一个用作外循环的promise数组。

Parse.Cloud.define("getFriends", function (request, response) {
  var _ = require('underscore.js');
  var queryFields = request.params.queryFields;
  //var ClassToSearch = Parse.Object.extend("User");

  var promises = [];
  var promises2 = [];
  var FinalResult = [];
 var asyncFunc = function (userIDArray) {
    _.each(queryFields, function (queryField) {
      var query = new Parse.Query(Parse.User);
      query.equalTo("yourColumnName", queryField);
      promises.push(
        query.find().then(function (results) {
       _.each(results, function (resultObj) { 
        //nested query
        var ClassToSearch = Parse.Object.extend("AnotherColumn");
        var query2 = new Parse.Query(ClassToSearch);
        query2.equalTo("yourColumnName", resultObj);
        promises2.push(        
          query2.first().then(function (itinerary) {
          FinalResults.push(itinerary);
        }));

      });
      return Parse.Promise.when(promises2);
    })
          )
    });
    // Return a new promise that is resolved when all of the requests are done 
    return Parse.Promise.when(promises);
  };
  asyncFunc(queryFields).then(function () {
    console.log("all http requests were made");
    response.success(FinalResults);
  }, function (error) {
    console.log("there was some error");
  });
});