Backendless Support
 
Answered

Load All Objects Using Javascript for Custom Business Logic

I am trying to implement the feature listed in feature 17, which gives sample code on how to load all the objects. Basically, I want to load all the objects from a given table in the server side code in business logic. I am having trouble doing this as the requests are all async and I feel like I am overcomplicating it. Right now I am unwrapping the promise object from the find operation, but I cant seem to get it to work under the while loop. Anytime I call the nextPage() it gives a promise object, which is fine for one result, but I want it to iterate through all the results. Any example code I can use or help?

var PlaceHitStore = Backendless.Data.of('Place_Hits');

var placeHitDataQuery = new Backendless.DataQuery();

placeHitDataQuery.options = {

pageSize:10

};

var restaurants = PlaceHitStore.find(placeHitDataQuery);

restaurants.then(function(result){

console.log( "Total restaurants - " + result.totalObjects);

var size = result.data.length;

console.log(" initial loaded " + size);

var nextPage = result._nextPage;

var count = 0;

while (nextPage){

restaurants = restaurants.nextPage();

//Do I unwrap the promise again? This is where i have trouble

size = restaurants.data.length;

console.log( "Loaded " + size + " restaurants in the current page" );

nextPage = restaurants._nextPage;

}

});

Leave a Comment

Comments (1)

photo
2

Hi Patrick

Try this

  1. Backendless.enablePromises();
  2. function findAllPlaceHits() {
  3. var dataStore = Backendless.Data.of('Place_Hits');
  4. var dataQuery = new Backendless.DataQuery();
  5. dataQuery.options = {
  6. pageSize:100
  7. };
  8. var placeHits = [];
  9. return new Promise((resolve, reject) => {
  10. const handleResult = result => {
  11. placeHits = placeHits.concat(result.data);
  12. if (result.nextPage) {
  13. result.nextPage().then(handleResult, reject);
  14. } else {
  15. //we reached the last page - it's time to resolve the promise
  16. resolve(placeHits);
  17. }
  18. }
  19. dataStore.find(placeHitDataQuery).then(handleResult, reject)
  20. })
  21. }
  22. //custom business logic example
  23. Backendless.ServerCode.customEvent('myCustomEvent', function() {
  24. return findAllPlaceHits(restorants => {
  25. //do whatever you need with restorants and return wanted result to the caller
  26. })
  27. })