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;

}
});

Hi Patrick
Try this

Backendless.enablePromises();


function findAllPlaceHits() {
  var dataStore = Backendless.Data.of('Place_Hits');
var dataQuery = new Backendless.DataQuery();


dataQuery.options = {
pageSize:100
};


var placeHits = [];


return new Promise((resolve, reject) => {


const handleResult = result => {
placeHits = placeHits.concat(result.data);


if (result.nextPage) {
result.nextPage().then(handleResult, reject);
} else {
//we reached the last page - it's time to resolve the promise 
resolve(placeHits);
}
}


dataStore.find(placeHitDataQuery).then(handleResult, reject)
})
}


//custom business logic example
Backendless.ServerCode.customEvent('myCustomEvent', function() {
return findAllPlaceHits(restorants => {
//do whatever you need with restorants and return wanted result to the caller
})
})