-1
function getCategory(categoryId){
  var TrainingPackage = Parse.Object.extend("TrainingPackage");
  var query = new Parse.Query(TrainingPackage);

  query.equalTo("category_id", "12asfas234");
  query.find({
  success: function(results) {
      return results; 
    }
  },
  error: function(error) {
    console.error("Error: " + error.code + " " + error.message);
  }
});

console.log(getCategory());

doSomething(getCategory());

1) When I run the above code, the output I get is "undefined" because I'm guessing it doesn't wait until the results are returned?

How do I save the value of the results from the query OUTSIDE of the function?

2) If I want to make any query based on the results of the 1st query, how do I do that? How can I make the doSomething(getCategory()) wait for the response?

I've looked into promises and callbacks but it's all very confusing!

Keith Rumjahn
  • 461
  • 3
  • 8
  • 16

1 Answers1

1

Such type of asynchronous activity should be handled by callbacks. Query.find() is an asynchronous action. You have to attach a callback to the success event. So this callback will only be executed after query.find() has successfully finished fetching data.

function getCategory(categoryId,callback){
  var TrainingPackage = Parse.Object.extend("TrainingPackage");
  var query = new Parse.Query(TrainingPackage);

  query.equalTo("category_id", "12asfas234");
  query.find({
  success: function(results) {
  callback(results);
  //return results; 
    }
   },
  error: function(error){
  console.error("Error: " + error.code + " " + error.message);
 }
 });


getCategory(id,function(results){
   console.log(results);
  }));

getCategory(id,function(results){
    doSomething()
   });
rishabh dev
  • 1,711
  • 1
  • 15
  • 26