如何在第一个查询完成后在parse.com上调用第二个查询(云代码)

时间:2013-11-05 16:34:30

标签: javascript parse-platform

我的挑战是我需要在另一个查询之前执行一个查询,使用第一个查询的结果作为第二个查询中的输入。

var adList = [];
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
        objectIDArray.push(results[i].id);  
    }
},
error: function(){
    response.error("failed");
}   
});
    //second query
var locations = Parse.Object.extend("Locations");
query2.include("locationID");
query2.containedIn("campaignIDString", objectIDArray);
query2.find({
    success: function(results){
        locations = results2[0].get("locationID");
        adList.push(locations.get("CITY"));
        adList.push(locations.get("PROVINCE"));
        adList.push(locations.get("STORE_ADDRESS"));

        response.success(adList);
    }, error: function(){ 
        response.error("failed to get a response");
        }
});

如您所见,在第二个查询中,我需要objectIDArray,它由第一个查询填充。如果我运行这个,我总是在第二个查询中得到null结果,因为两个查询似乎并行发生。无论如何,他们不会像我希望的那样顺序发生。 如何在第一个查询之后运行第二个查询?使用承诺?

你能给我一个例子,我不能很好地理解文件

1 个答案:

答案 0 :(得分:2)

将第二个查询移到第一个查询的完成块中:

var adList = [];
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
        objectIDArray.push(results[i].id);  
    }

    //second query
    var locations = Parse.Object.extend("Locations");
    query2.include("locationID");
    query2.containedIn("campaignIDString", objectIDArray);
    query2.find({
        success: function(results){
            locations = results2[0].get("locationID");
            adList.push(locations.get("CITY"));
            adList.push(locations.get("PROVINCE"));
            adList.push(locations.get("STORE_ADDRESS"));

            response.success(adList);
        }, error: function(){ 
            response.error("failed to get a response");
            }
    });
},
error: function(){
    response.error("failed");
}   
});

或者您可以使用Promises

相关问题