1

我的挑战是我需要先执行一个查询,将第一个查询的结果用作第二个查询的输入。

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。如果我运行它,我总是在第二个查询中得到空结果,因为这两个查询似乎是并行发生的。无论如何,它们不会像我希望的那样依次发生。如何让我的第二个查询在第一个查询之后运行?使用承诺?

你能给我举个例子吗,我不能很好地理解这些文件

4

1 回答 1

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

于 2013-11-05T17:07:19.587 回答