Clifton Labrum
Clifton Labrum

Reputation: 14068

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.

Upvotes: 2

Views: 1447

Answers (2)

Vaclav Matouch
Vaclav Matouch

Reputation: 11

Just to update Wain's structured code: Promise.when returns array when supplied with an array, so the correct code would be

Parse.Promise.when(promises).then(function([result1, result2]) {

and since there is no need to repack the array, it would simply be

Parse.Promise.when(promises).then(function(result) {
   response.success(result);

See here for more info.

Upvotes: 1

Wain
Wain

Reputation: 119031

  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);
});

}

Upvotes: 5

Related Questions