Search code examples
backbone.jsparse-platformparse-cloud-code

Multiple Queries with Parse Cloud Code Using Promises


I have two questions:

  1. Is the below example the right way to execute multiple Parse queries in a single Cloud Code function?
  2. Is the below example going to provide all the data I'm querying with one HTTP request (when I call logbookEntries) and then count as two Parse requests on my account because it's two Parse queries?

Here's the code:

Parse.Cloud.define("logbookEntries", function(request, response) {

  //::: Query 1 :::
  var firstQuery = new Parse.Query("Logbook");
  var returnData = []; 

  firstQuery.find().then(function(firstResults) {
    returnData[0] = firstResults; 

  }).then(function(result) {  

    //::: Query 2 :::
    var secondQuery = new Parse.Query("Logbook"); 
    secondQuery.find().then(function(secondResults))
    returnData[1] = secondResults; 

  }).then(function(result) {
    response.success(returnData);

  }, function(error) {
    response.error(error);

  });
});

Thanks in advance.


Solution

    1. It's one way, though not quite correct.
    2. Yes

    Your code should really be:

    Parse.Cloud.define("logbookEntries", function(request, response) {
    
    //::: Query 1 :::
    var firstQuery = new Parse.Query("Logbook");
    var returnData = []; 
    
    firstQuery.find().then(function(firstResults) {
       returnData[0] = firstResults; 
    
       var secondQuery = new Parse.Query("Logbook"); 
       return secondQuery.find();
    }).then(function(result) {
       returnData[1] = result; 
    
       response.success(returnData);
    
    }, function(error) {
       response.error(error);
    });
    
    });
    

    Or, a better way to structure it would be:

    Parse.Cloud.define("logbookEntries", function(request, response) {
    
    var firstQuery = new Parse.Query("Logbook");
    var secondQuery = new Parse.Query("Logbook");
    
    var promises = [];
    promises.push(firstQuery.find());
    promises.push(secondQuery.find());
    
    Parse.Promise.when(promises).then(function(result1, result2) {
       var returnData = [];
       returnData[1] = result1; 
       returnData[2] = result2; 
    
       response.success(returnData);
    
    }, function(error) {
       response.error(error);
    });
    
    }